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.

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
2

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

1 Comment

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.
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>)

Comments

0

You want to do this instead

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

Your multipliers are messing things up.

1 Comment

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.
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.

1 Comment

Even so that doesn't account for making the byte 0x50 into 0x0b.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.