我有一个数组,我试图转换为字节数组。但是我很难找到正确的逻辑。
这是我的位数组数据:
1111 11111111 11111111 11111111 11101101
最终结果为:
[0]: 00011010 //this is obviously wrong should be: 11101101
[1]: 11111111
[2]: 11111111
[3]: 11111111
[4]: 11111111 // also obviously wrong should be :00001111
这显然是不对的,但目前还无法弄清楚正确的逻辑。
这是我的比特流课程中的方法:
public void GetByteArray(byte[] buffer)
{
//1111 11111111 11111111 11111111 11101101
int totalBytes = Mathf.CeilToInt(Pointer / 8f);
int pointerPos = Pointer - 1; // read back should not change the current bitstream index
for (int i = totalBytes-1; i >= 0; --i)
{
int counter = 0; // next byte when == 8
for (int j = pointerPos; j >= 0; --j)
{
counter++;
pointerPos--;
if (BitArray[j]) // if bit array [j] is true then `xor` 1
buffer[i] |= 1;
// we don't shift left for counter==8 to avoid adding extra 0
if (counter < 8)
buffer[i] = (byte)(buffer[i] << 1);
else
break; //next byte
}
}
}
任何人都可以在这里看到我的逻辑错误吗?