How do you convert 3 bytes to a 24 bit number in C #?

I have an array of bytes that I read from the message header section. These bytes contain the length of the message. There are never more than 3 bytes, and they are ordered from LSB to MSB. Thus, in the example below, 39 is an LSB and 2 is an MSB.

var data = new byte[] { 39, 213, 2 }; 

In the above example, how can I take these bytes and convert to a number (int, short, etc.)?

+4
source share
5 answers
 var num = data[0] + (data[1] << 8) + (data[2] << 16); 
+13
source

Use methods such as BitConverter.ToInt32 , but understand that you will need 4 bytes for 32-bit values.

 var data = new byte[] {39, 213, 2, 0}; int integer = BitConverter.ToInt32(data, 0); 

There are also other methods for converting to and from other types, such as Single and Double .

+9
source

Use the left shift operator and the or operator:

 int d = (data[2] << 16) | (data[1] << 8) | data[0] 

Obviously, you could do all kinds of things, for example, using a loop, etc. :)

+5
source

Something like this should work:

 data[0] + 256*data[1] + 256*256*data[2] 

Your compiler should optimize this for the โ€œcorrectโ€ bit-folding operations.

+1
source

BitConverter handles the continent for you, which is why this is the way to go.

As long as you need 4 bytes do

 BitConverter.ToInt32(new byte[1] { 0 }.Concat(yourThreeByteArray).ToArray()); 
0
source

All Articles