Search code examples
c++arraysunsignedunsigned-char

Convert array of unsigned char (byte) into unsigned short in C++


I have array^ byteArray and I need to extract bytes in Little Endian sequence to make unsigned shorts and ints. I've tried every combination of the following I can think of so am asking for help.

int x = UInt32(byteArray[i]) + (UInt32)(0x00ff) * UInt32(byteArray[i + 1]);
int x = UInt32(byteArray[i]) + UInt32(0x00ff) * UInt32(byteArray[i + 1]);
int x = byteArray[i] + 0x00ff * byteArray[i + 1];

The problem is the least significant byte (at i+1) I know it is 0x50 but the generated short/int reports the lower byte as 0x0b. The higher byte is unaffected.

I figure this is a sign error but I can't seem to be able to fix it.


Solution

  • You are using managed code. Endian-ness is an implementation detail that the framework is aware of:

    array<Byte>^ arr = gcnew array<Byte> { 1, 2, 3, 4 };
    int value = BitConverter::ToInt16(arr, 1);
    System::Diagnostics::Debug::Assert(value == 0x302);
    

    Whether the framework's assumptions are correct depends on where the data came from.