Search code examples
c#bytedata-conversion

Take 4 bits out of an int and convert to byte


I am implementing a serial protocol.

I need to take class members and pack them into a byte[] message.

Protocol byte #7 goes like this:

Bit 0-3 - SomeNumricData

Bit 0-4 - OtherNumericData

I am trying to build byte #7 from class members :

commandData[7] = Convert.ToByte(

            Convert.ToByte(SomeNumricData) |
            Convert.ToByte(OtherNumericData) << 4
            );

I get:

System.OverflowException: 'Value was either too large or too small for an unsigned byte

Since there is no 4 bits data type... How can I get only 4 bits out of the integer, to not overflow the Convert.ToByte()?


Solution

  • You are providing a number that is overflowing. You could use the code bellow, but it will take only the four least significant bits. If the number is greater than 0x0F, the other bits will be ignored.

    commandData[7] = Convert.ToByte((SomeNumricData & 0x0F) | ((OtherNumericData << 4) & 0xF0));