我有一个将BitArray值转换为byte[]值的代码。我也从堆栈溢出中得到了代码。
代码运行得很好,我只是不明白其中的一个部分。
当代码使用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)发布于 2019-08-06 10:33:44
因为我们从右数位,从左数项;例如
BitArray myBitArray = new BitArray(new byte[] { 10 });我们有byte 10 (从右数):
10 = 00001010 (binary)
^
second bit (which is 1)当对应数组的项从左边计数时:
{false, true, false, true, false, false, false, false}
^
corresponding second BitArray item (which is true)这就是为什么如果我们想要返回一个byte数组,我们必须对每个byte表示进行Reverse,例如Linq解决方案
using System.Collections;
using System.Linq;
...
BitArray myBitArray = ...
byte[] myByte = myBitArray
.OfType<bool>()
.Select((value, index) => new { // into chunks of size 8
value,
chunk = index / 8 })
.GroupBy(item => item.chunk, item => item.value)
.Select(chunk => chunk // Each byte representation
.Reverse() // should be reversed
.Aggregate(0, (s, bit) => (s << 1) | (bit ? 1 : 0)))
.Select(item => (byte) item)
.ToArray();https://stackoverflow.com/questions/57373070
复制相似问题