Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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

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

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

like image 297
legion Avatar asked Jul 27 '10 16:07

legion


2 Answers

var num = data[0] + (data[1] << 8) + (data[2] << 16);
like image 129
ChaosPandion Avatar answered Oct 21 '22 06:10

ChaosPandion


Use methods like BitConverter.ToInt32, but realize that you'll need 4 bytes for 32 bit quantities.

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

There are also other methods to convert to and from other types like Single and Double.

like image 27
Jeff Moser Avatar answered Oct 21 '22 06:10

Jeff Moser