0

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.

John
  • 6,433
  • 7
  • 47
  • 82

5 Answers5

3

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.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • On the MSDN help page I find ToInt16 sample indicating the array 01-02-03-04 yields ToInt16(arr, 1) == 0x20. Unless I missed something. Thanks for the speedy expertise offered. – John Sep 24 '11 at 23:30
2

The proper way to generate an 16 bit int from two 8 bit ints is value = static_cast< int16_t >( hibyte ) << 8 | lobyte;

K-ballo
  • 80,396
  • 20
  • 159
  • 169
  • You should also cast `hibyte` to the 16-bit data type, otherwise, if it is an 8-bit data type, the left shift will turn it into a 0. – Praetorian Sep 24 '11 at 23:00
1
int y = byteArray[i] | byteArray[i + 1] << 8;

is what you need to use. (see also Convert a vector<unsigned char> to vector<unsigned short>)

Community
  • 1
  • 1
John
  • 6,433
  • 7
  • 47
  • 82
0

You want to do this instead

int x = UInt32(byteArray[i]) | (UInt32(byteArray[i + 1]) << 8);

Your multipliers are messing things up.

Mark Robinson
  • 3,135
  • 1
  • 22
  • 37
  • You're trying to do a shift. The multiplication can emulate a shift but you're multiplying by 255 which won't emulate a shift. – Mark Robinson Sep 24 '11 at 23:13
0

You have to multiply the second byte with 0x0100 instead of 0x00ff.

It's like in the decimal system, where you multiply by ten, not by nine.

Roland Illig
  • 40,703
  • 10
  • 88
  • 121