gpt4 book ai didi

c# - BitArray 以错误的方式返回位?

转载 作者:可可西里 更新时间:2023-11-01 08:08:27 25 4
gpt4 key购买 nike

这段代码:

BitArray bits = new BitArray(new byte[] { 7 });
foreach (bool bit in bits)
{
Console.WriteLine(bit ? 1 : 0);
}

给我以下输出:

11100000

不应该反过来吗?像这样:

00000111

我知道有小端和大端,尽管这些术语仅指字节的位置。据我所知,它们不会影响位。

最佳答案

documentation for BitArray状态:

The first byte in the array represents bits 0 through 7, the second byte represents bits 8 through 15, and so on. The Least Significant Bit of each byte represents the lowest index value: " bytes [0] & 1" represents bit 0, " bytes [0] & 2" represents bit 1, " bytes [0] & 4" represents bit 2, and so on.

在对位进行索引时,约定是从最低有效端开始,即用二进制表示法书写时的右侧。但是,在枚举数组时,您从索引 0 开始,因此它们是从左到右而不是从右到左打印的。这就是它向后看的原因。

例如,单词 01011010 00101101 (90 45) 将被索引为:

 0  1  0  1  1  0  1  0  -  0  0  1  0  1  1  0  1
----------------------- -----------------------
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

并且您会将它作为 new byte[] { 45, 90 } 传递给构造函数,因为您首先将它传递给最不重要的。打印出来时,它将按索引顺序显示为:1011010001011010,这与原始二进制表示法相反。

关于c# - BitArray 以错误的方式返回位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9066831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com