Search code examples
c#bit

Bit isn't on as expected


I'm converting a number to a byte array via the following method:

var bytes = new Span<byte>(new byte[4]);
BinaryPrimitives.WriteInt32BigEndian(bytes.ToArray(), <my-number>);

I'm then converting the byte array to a BitArray (for testing purposes).

var arr = new BitArray(bytes);

And testing to make sure the last bit is on (I'm using it as a flag).

Assert.True(arr[^1]);

However, this is returning false. This doesn't make sense to me, since my last byte in the array has a value of 29. Which, if I'm thinking correctly, would be 00011101 -- the last bit is on.

To further confuse me, if I use WriteInt32*Little*Endian, the bit at position 0 is on as I'd expect.

I'm sure this is something simple, but I'm thoroughly confused as to why my last bit isn't on as expected.

EDIT: Supplied code in testable format, as requested.

var bytes = new Span<byte>(new byte[4]);
BinaryPrimitives.WriteInt32BigEndian(bytes, 1023773);
var arr = new BitArray(bytes.ToArray());
Assert.True(arr[^1]);

Solution

  • Sometimes it's worth checking the docs...

    For BitArray(byte[]):

    The first byte in the array represents bits 0 through 7, the second byte represents bits 8 through 15, and so on.

    So while you're getting big-endian bytes, the BitArray constructor is effectively little-endian: the least-significant byte is passed first.

    This explains why WriteInt32LittleEndian performed as you expected: it produced the bytes in the same endianness that BitArray was expecting.