Search code examples
c#bytebit

C# Get Bits from Byte


I don't know why I am getting wrong bits when reading my byte. I have followed some indications found here, bit it is not working. I show you my code:

byte[] byte22And23 = _packet.ReadBytes(2);
DataFromGTAPackets.Packet8.ControlFlags.rightEngineSmoke = _packet.GetBit(byte22And23[0], 0);
DataFromGTAPackets.Packet8.ControlFlags.leftEngineSmoke = _packet.GetBit(byte22And23[0], 1);
DataFromGTAPackets.Packet8.ControlFlags.rightEngineFire = _packet.GetBit(byte22And23[0], 2);
DataFromGTAPackets.Packet8.ControlFlags.leftEngineFire = _packet.GetBit(byte22And23[0], 3);
DataFromGTAPackets.Packet8.ControlFlags.rightRotorFail = _packet.GetBit(byte22And23[0], 4);
DataFromGTAPackets.Packet8.ControlFlags.leftRotorFail = _packet.GetBit(byte22And23[0], 5);
etc...
public bool GetBit(byte b, int bitNumber)
    {
        bool bit = (b & (1 << bitNumber - 1)) != 0;
        return bit;
    }

My byte 22 has a value of 2, it is: 00000010. And my byte 23 has a value of 0. When I use this code to read byte 22, my 3rd variable (rightEngineFire) is getting "true" (1). It has no sense, it is wrong obviously. But I don't know what is wrong.

Thank you!


Solution

  • The GetBit() implementation is wrong, you can check with the following test:

    [TestMethod]
    public void MyTestMethod()
    {
        var byte22And23 = new byte[] { 2, 0 };
        var sb = new StringBuilder();
        for (int i = 7; i >=0; i--)
        {
            var r = GetBit(byte22And23[0], i);
            sb.Append((r) ? "1" : "0");
        }
    
        // result: 00000100
        Assert.AreEqual("00000010", sb.ToString());
    }
    

    It looks like there is no need of -1 in GetBit() because you are indexing bits 0-based and not 1-based:

    public bool GetBit(byte b, int bitNumber)
    {
        // no need of -1 here ------------ˇ
        bool bit = (b & (1 << bitNumber - 1)) != 0;
        return bit;
    }
    

    After the modification the tests runs green.