【发布时间】:2014-05-18 01:23:17
【问题描述】:
我需要将整数值序列化为字节数组Byte[],这样输入值的最高有效位也是目标数组中的最高有效位。它还需要允许存储位置的每位(而不是每字节)偏移量。
这是一个简单的例子,我正在编写一个与字节边界对齐的整数(MSByte-first,MSbit-first-order):
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 );
这里有类似的东西,但偏移了 1 位:
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 );
我目前正在使用BitArray 实例,但是BitArray 反转字节内的位顺序,即。 bitArray[0] 是其缓冲区中第一个字节的最低有效位,而我需要它是缓冲区中第一个字节的最高有效位。
【问题讨论】:
标签: .net endianness bitarray