0

简单的问题:

我如何判断字节中的哪些位设置为 0,哪些设置为 1

例如:

//That code would obviously wont work, but how do i make something similar that would work?
byte myByte = 0X32;

foreach(bool bit in myByte)
{
  Console.WriteLine(bit);
}


//Part 2 revert
bool[] bits = new bool[8];
bits[0] = 0
bits[1] = 0
bits[2] = 0
bits[3] = 0
bits[4] = 0
bits[5] = 1
bits[6] = 0
bits[7] = 0

byte newByte = (byte)bits;

整个互联网充满了例子,但我就是想不通

4

3 回答 3

5

你想使用位操作

k = bits = 0;
for (i = 1; i < 256; i <<= 1)
  bool[k++] = (bits & i) != 0;


k = bits = 0;
for (i = 1; i < 256; i <<= 1)
  if (bool[k++]) bits |= i;
于 2009-02-24T07:24:01.143 回答
1

BitArrayclass 将是可能的最简单(尽管不一定是最快)的方式。

于 2009-02-24T07:23:25.107 回答
0

你可以和他们。如果在两个数字中都设置了 1 位,它将保持设置状态。我不确定那个样本到底是什么,但是用 1 加一点会给你一个真(1)或假(0)。

0010 & 1010 = 0010

于 2009-02-24T07:22:10.553 回答