I read 3 bytes in a binary file which I need to convert into an integer.
I use this code to read the 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 an integer
.
This seems to be the good way to convert bytes
into integers
in the posts i have seen.
Here is a capture of the values read:
But the integer last1Hz.NumData
is always 0.
I'm missing something but can't figure out what.
You need to use brackets (because addition has a higher priority than bit shifting):
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];