0
votes

I am unpacking a byte[] content into a bunch of fields. Most of it directly maps from field to type (eg 4 bytes = Uint32). There are some that are fields packed into a byte. eg 8 bools, or 2bits + 4 bits + bool + bool. In the constructor below I try to parse the content into class properties.

public RFTagLost(byte[] content)
{
    byte flags1;
    UInt16 flags2;

    int i = 0;

    GatewaySerial = BitConverter.ToUInt32(content, i);
    i += sizeof(UInt32);

    SerialNumber = BitConverter.ToUInt32(content, i);
    i += sizeof(UInt32);

    Token = BitConverter.ToUInt32(content, i);
    i += sizeof(UInt32);

    flags1 = content[i];
    i += sizeof(byte);
    // TODO parse flags
    GatewayMode = (byte)((flags1 >> 0) & 3);            // 2 bits
    LinkType = (byte)((flags1 >> 2) & 3);               // 2 bits
    Reserved = (byte)((flags1 >> 4) & 15);              // 4 bits

    TagType = content[i];
    i += sizeof(byte);

    flags2 = BitConverter.ToUInt16(content, i);
    i += sizeof(UInt16);
    LastSeen = (UInt16)((flags2 >> 0) & 32767);           // 15 bits
    LastSeenInMinutes = (bool)((flags2 >> 15) & 1);     // 1 bit
}           

I was having problems with the shift and mask operations returning an int. I finally worked out that despite flag1 being a byte, bitwise was returning an int that was causing my assign to property to fail. Same with flag2.

Now my error is that

Cannot convert type 'int' to 'bool'

This is when trying to extract the last field. It's the last bit in a UInt16

Am I doing the right thing to extract these bit fields. What do I do to make bool LastSeenInMinutes work?

1

1 Answers

1
votes

To convert an int to a bool, you can just test the result for equality with 1 or 0.

LastSeenInMinutes = ((flags2 >> 15) & 1) == 1;