Search code examples
c#binaryarraysbytetwos-complement

Convert 2 bytes to a number


I have a control that has a byte array in it.

Every now and then there are two bytes that tell me some info about number of future items in the array.

So as an example I could have:

...
...
Item [4] = 7
Item [5] = 0
...
...

The value of this is clearly 7.

But what about this?

...
...
Item [4] = 0
Item [5] = 7
...
...

Any idea on what that equates to (as an normal int)?

I went to binary and thought it may be 11100000000 which equals 1792. But I don't know if that is how it really works (ie does it use the whole 8 items for the byte).

Is there any way to know this with out testing?

Note: I am using C# 3.0 and visual studio 2008


Solution

  • 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]