PC Review


Reply
Thread Tools Rate Thread

C# Equivalent of C++ statement

 
 
Tina
Guest
Posts: n/a
 
      10th Jan 2012
I am trying to write the C# equivalent for the following bit of C++
code. What is the C# equivalent to the following line:

unsigned short* p16bitComponents = reinterpret_cast<unsigned
short*>( pLineIn );

Since we cannot downcast from uint to short in C#, how can I access
the first 16 bits of my 32 bit data line?

void DoSomething(unsigned int* pLineIn, unsigned short * pLineOut, int
lineLength)
{
unsigned short he;
unsigned short le;

unsigned short* p16bitComponents = reinterpret_cast<unsigned short
*>( pLineIn );

for (S32 i = 0; i < lineLength; i++)
{
le = *p16bitComponents++;
he = *p16bitComponents++;

// do something with le and he
}
}
 
Reply With Quote
 
 
 
 
Marcel Müller
Guest
Posts: n/a
 
      10th Jan 2012
On 10.01.2012 21:13, Tina wrote:
> I am trying to write the C# equivalent for the following bit of C++
> code. What is the C# equivalent to the following line:
>
> unsigned short* p16bitComponents = reinterpret_cast<unsigned
> short*>( pLineIn );


Do you want to write Assemblies that only compile with the unsafe option?
If not, then your question does not matter since there are no pointer
types in C# without the unsafe option. So you cannot cast them.

> Since we cannot downcast from uint to short in C#,


Of course, you can cast from uint to ushort.

> how can I access
> the first 16 bits of my 32 bit data line?
>
> void DoSomething(unsigned int* pLineIn, unsigned short * pLineOut, int
> lineLength)
> {
> unsigned short he;
> unsigned short le;
>
> unsigned short* p16bitComponents = reinterpret_cast<unsigned short
> *>( pLineIn );

This line is undefined behavior in C++. The code is broken.
On a certain platform the code might behave deterministic, but it is
non-portable.

> for (S32 i = 0; i< lineLength; i++)
> {
> le = *p16bitComponents++;
> he = *p16bitComponents++;
>
> // do something with le and he
> }
> }


If you want to port this to .NET, you have to find replacements for the
pointer types. In C pointer types are often arrays. In C++ this is bad
practice, mainly supported for compatibility.
If you have this, then the following is probably obvious. Casting from
uint to ushort will extract the lower 16 bits. In contrast to the above
C++ code, that will badly fail on big endian hardware like Motorola and
ARM, the .NET cast is portable. To extract the higher 16 bits of the int
use the expression
(ushort)(my_uint_value >> 16)


Marcel
 
Reply With Quote
Reply

Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off



Features
 

Advertising
 

Newsgroups
 


All times are GMT +1. The time now is 10:35 AM.