从字节中获取bool,反之亦然

时间:2009-02-24 07:18:57

标签: math casting binary types

简单问题:

如何判断字节中的哪些位设置为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;

互联网上充满了各种各样的例子,但我无法弄清楚

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分:1)

BitArray类将是最简单的(尽管不一定是最快)类。

答案 2 :(得分:0)

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

0010&amp; 1010 = 0010