C# Equivalent of C++ statement

T

Tina

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
}
}
 
M

Marcel Müller

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top