简体   繁体   English

遍历 C# 中的所有字节位

[英]Iterate over all bits of byte in C#

I am working on a C# application.我正在开发 C# 应用程序。 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:这段代码给了我以下 output:

Length of collection : 3
False
False
False

But as the binary representation of 3 is 00000011 so i expect the following output但是由于 3 的二进制表示是 00000011 所以我期望以下 output

False
False
False
False
False
False
True
True

What am i doing wrong?我究竟做错了什么? How can i achieve the required output我怎样才能达到所需的 output

You're calling the BitArray(int length) constructor:您正在调用BitArray(int length)构造函数:

Initializes a new instance of the BitArray class that can hold the specified number of bit values, which are initially set to false.初始化 BitArray class 的新实例,该实例可以保存指定数量的位值,这些值最初设置为 false。

So you're creating a BitArray of length 3, not a BitArray which contains the bits from the integer value 3.因此,您正在创建一个长度为 3 的BitArray ,而不是包含来自 integer 值 3 的位的BitArray

You want the BitArray(byte[] bytes) constructor:你想要BitArray(byte[] bytes)构造函数:

Initializes a new instance of the BitArray class that contains bit values copied from the specified array of bytes.初始化包含从指定字节数组复制的位值的 BitArray class 的新实例。

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]);
}

Outputs:输出:

Length of collection : 8
True
True
False
False
False
False
False
False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM