Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Byte shift issue in an integer conversion

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:

enter image description here

But the integer last1Hz.NumData is always 0.

I'm missing something but can't figure out what.

like image 938
Alexus Avatar asked Jan 27 '26 01:01

Alexus


1 Answers

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];
like image 194
Romano Zumbé Avatar answered Jan 29 '26 14:01

Romano Zumbé



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!