遍历C#中字节的所有位 [英] Iterate over all bits of byte in C#
问题描述
我正在开发C#应用程序.我有一个字节变量,我想遍历它的所有位.
I am working on a C# application. I have a byte variable, i want to iterate over all bits of it.
byte var = 3;
System.Collections.BitArray bits = new System.Collections.BitArray(var);
Console.WriteLine("Length of collection : " + bits.Length);
for (int i = 0; i < bits.Length; i++)
{
Console.WriteLine(bits[i]);
}
这段代码为我提供了以下输出:
This code gives me the following output:
Length of collection : 3
False
False
False
但是由于3的二进制表示形式是00000011,所以我期望以下输出
But as the binary representation of 3 is 00000011 so i expect the following output
False
False
False
False
False
False
True
True
我在做什么错?我如何获得所需的输出
What am i doing wrong ? How can i achieve the required output
推荐答案
You're calling the BitArray(int length)
constructor:
初始化BitArray类的新实例,该实例可以保存指定数量的位值,这些位值最初设置为false.
Initializes a new instance of the BitArray class that can hold the specified number of bit values, which are initially set to false.
因此,您正在创建长度为3的BitArray
,而不是包含整数值3中的位的BitArray
.
So you're creating a BitArray
of length 3, not a BitArray
which contains the bits from the integer value 3.
You want the BitArray(byte[] bytes)
constructor:
初始化BitArray类的新实例,该实例包含从指定的字节数组复制的位值.
Initializes a new instance of the BitArray class that contains bit values copied from the specified array of bytes.
byte var = 3;
BitArray bits = new BitArray(new byte[] { var });
Console.WriteLine("Length of collection : " + bits.Length);
for (int i = 0; i < bits.Length; i++)
{
Console.WriteLine(bits[i]);
}
输出:
Length of collection : 8
True
True
False
False
False
False
False
False
这篇关于遍历C#中字节的所有位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!