Search code examples
c#binaryintarraysbitconverter

Why I can't convert a byte[2] array to int with BitConverter?


The main problem is that I recive a binary number with only 10 bits in use from a SerialPort so I use this to receive the complete data:

byte[] buf = new byte[2];
serialPort.Read(buf, 0, buf.Length);
BitArray bits = new BitArray(buf);

The original idea for convert binary to int was this:

foreach (bool b in bits)
{
    if(b){
        binary += "1";
    }
    else{
        binary+= "0";
    }
}

decimal = Convert.ToInt32(binary, 2); 
decimal = decimal >> 6;

binary is obviously a string, that works but I need to know if exists another solution, instead of the previuos code I try with this:

decimal = BitConverter.ToInt16(buf, 0);

But this only read the first 8 bits, I need the other 2 bits missing! If I change ToInt16 for a ToInt32

decimal = BitConverter.ToInt32(buf, 0);

The program stops for a System.ArgumentException: Destination array was not long enough...

What can I do?


Solution

  • You can just shift the values in the bytes so that they match, and put them together. If I got the use of bits right, that would be:

    int value = (buf[0] << 2) | (buf[1] >> 6);