Byte shift problem in integer conversion
I am reading 3 bytes in a binary that I need to convert to an integer.
I am using this code to read bytes:
LastNum last1Hz = new LastNum();
last1Hz.Freq = 1;
Byte[] LastNumBytes1Hz = new Byte[3];
Array.Copy(lap_info, (8 + (32 * k)), LastNumBytes1Hz, 0, 3);
last1Hz.NumData = LastNumBytes1Hz[2] << 16 + LastNumBytes1Hz[1] << 8 + LastNumBytes1Hz[0];
last1Hz.NumData
is integer
.
This seems to be a good way to convert bytes
to integers
in posts I've seen.
Here is a capture of the values ββread:
But the integer is last1Hz.NumData
always 0.
I'm missing something but can't figure out what.
+3
source to share
2 answers
You need to use parentheses (because append has higher precedence than bit offset):
int a = 0x87;
int b = 0x00;
int c = 0x00;
int x = c << 16 + b << 8 + a; // result 0
int z = (c << 16) + (b << 8) + a; // result 135
Your code should look like this:
last1Hz.NumData = (LastNumBytes1Hz[2] << 16) + (LastNumBytes1Hz[1] << 8) + LastNumBytes1Hz[0];
+4
source to share