Convert 2 bytes to a number

A two-byte number has a low and a high byte. The high byte is worth 256 times as much as the low byte:

value = 256 * high + low;

So, for high=0 and low=7, the value is 7. But for high=7 and low=0, the value becomes 1792.

This of course assumes that the number is a simple 16-bit integer. If it's anything fancier, the above won't be enough. Then you need more knowledge about how the number is encoded, in order to decode it.

The order in which the high and low bytes appear is determined by the endianness of the byte stream. In big-endian, you will see high before low (at a lower address), in little-endian it's the other way around.


You say "this value is clearly 7", but it depends entirely on the encoding. If we assume full-width bytes, then in little-endian, yes; 7, 0 is 7. But in big endian it isn't.

For little-endian, what you want is

int i = byte[i] | (byte[i+1] << 8);

and for big-endian:

int i = (byte[i] << 8) | byte[i+1];

But other encoding schemes are available; for example, some schemes use 7-bit arithmetic, with the 8th bit as a continuation bit. Some schemes (UTF-8) put all the continuation bits in the first byte (so the first has only limited room for data bits), and 8 bits for the rest in the sequence.


BitConverter can easily convert the two bytes in a two-byte integer value:

// assumes byte[] Item = someObject.GetBytes():
short num = BitConverter.ToInt16(Item, 4); // makes a short 
    // out of Item[4] and Item[5]