将 BitArray 转换为字节

BitArray我有一个将值转换为值的代码byte[]。我也从 stackoverflow 获得了代码。


代码运行得很好,我只是不明白一部分。


当代码复制到BitArray使用Byte读取BitArray.CopyTo()时byte按LSB 顺序。


有人可以帮我理解为什么转换后的字节是 LSB 顺序吗?


strBit (is a string value that consists of 1/0)

byte[] myByte = new byte[50];


List<string> list = Enumerable.Range(0, strBit.Length / 8)

    .Select(i => strBit.Substring(i * 8, 8))

    .ToList();


for (int x = 0; x < list.Count; x++)

{

    BitArray myBitArray = new BitArray(list[x].ToString().Select(c => c == '1').ToArray());

    myBitArray.CopyTo(myByte, x);

}

示例输出:


  strBit[0] = 10001111  (BitArray)

转换为字节时:


  myByte[0] = 11110001 (Byte) (241/F1)


HUX布斯
浏览 124回答 1
1回答

Qyouu

因为我们从右边开始计算位,从左边开始计算项目;例如对于&nbsp;BitArray myBitArray = new BitArray(new byte[] { 10 });我们有(byte 10从右数):&nbsp;10 = 00001010 (binary)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ^&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; second bit (which is 1)当相应数组的项目我们从左边开始计数时:&nbsp;{false, true, false, true, false, false, false, false}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;^&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;corresponding second BitArray item (which is true)这就是为什么如果我们想要一个byte后面的数组,我们必须Reverse每个byte表示,例如Linq解决方案&nbsp; using System.Collections;&nbsp; using System.Linq;&nbsp; ...&nbsp; BitArray myBitArray = ...&nbsp; byte[] myByte = myBitArray&nbsp; &nbsp; .OfType<bool>()&nbsp; &nbsp; .Select((value, index) => new { // into chunks of size 8&nbsp; &nbsp; &nbsp; &nbsp;value,&nbsp; &nbsp; &nbsp; &nbsp;chunk = index / 8 })&nbsp; &nbsp; .GroupBy(item => item.chunk, item => item.value)&nbsp; &nbsp; .Select(chunk => chunk // Each byte representation&nbsp; &nbsp; &nbsp; .Reverse()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// should be reversed&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; .Aggregate(0, (s, bit) => (s << 1) | (bit ? 1 : 0)))&nbsp; &nbsp; .Select(item => (byte) item)&nbsp; &nbsp; .ToArray();
打开App,查看更多内容
随时随地看视频慕课网APP