I need to serialize integer values to a byte array Byte[]
such that the most-significant-bit of the input value is also the most-significant-bit in the destination array. It also needs to allow for per-bit (not per-byte) offsets for storage locations.
Here's a simple example where I'm writing an integer (in both MSByte-first, MSbit-first-order) aligned to a byte-boundary:
Byte[] buffer = new Byte[99];
Encode( buffer, 0, 0x1234 ); // Encode the value 0x1234 inside buffer at bit-offset 0.
Assert.AreEqual( buffer[0], 0x12 ); // The integer value is stored most-significant-byte first
Assert.AreEqual( buffer[1], 0x34 );
Here's something similar, but offset by 1 bit:
Array.Initialize( buffer ); // Reset the buffer's bytes to 0.
Encode( buffer, 1, 0x0102 ); // Encode 0x0102 at bit-offset 1
// In binary 0x0102 is 00000001 00000010, but the final buffer will be this: 00000000 10000001 00000000
Assert.AreEqual( buffer[0], 0x00 ); // The first byte will be zero
Assert.AreEqual( buffer[1], 0x81 ); // 10000001 == 0x81
Assert.AreEqual( buffer[2], 0x00 );
I am currently using a BitArray
instance, however BitArray
reverses the bit-order within bytes, viz. bitArray[0]
is the least-significant-bit of the first byte in its buffer, whereas I need it to be the most-significant-bit of the first byte in my buffer.