Checking if a bit is set or not

2020-01-24 20:43发布

How to check if a certain bit in a byte is set?

bool IsBitSet(Byte b,byte nPos)
{
   return .....;
}

9条回答
劳资没心,怎么记你
2楼-- · 2020-01-24 21:23

Equivalent to Mario F code, but shifting the byte instead of mask:

bool IsBitSet(byte b, int pos)
{
   return ((b >> pos) & 1) != 0;
}
查看更多
三岁会撩人
3楼-- · 2020-01-24 21:23
x == (x | Math.Pow(2, y));

int x = 5;

x == (x | Math.Pow(2, 0) //Bit 0 is ON;
x == (x | Math.Pow(2, 1) //Bit 1 is OFF;
x == (x | Math.Pow(2, 2) //Bit 2 is ON;
查看更多
干净又极端
4楼-- · 2020-01-24 21:25

something like

return ((0x1 << nPos) & b) != 0
查看更多
仙女界的扛把子
5楼-- · 2020-01-24 21:32

sounds a bit like homework, but:

bool IsBitSet(byte b, int pos)
{
   return (b & (1 << pos)) != 0;
}

pos 0 is least significant bit, pos 7 is most.

查看更多
▲ chillily
6楼-- · 2020-01-24 21:33

This also works (tested in .NET 4):

void Main()
{
    //0x05 = 101b
    Console.WriteLine(IsBitSet(0x05, 0)); //True
    Console.WriteLine(IsBitSet(0x05, 1)); //False
    Console.WriteLine(IsBitSet(0x05, 2)); //True
}

bool IsBitSet(byte b, byte nPos){
    return new BitArray(new[]{b})[nPos];
}
查看更多
【Aperson】
7楼-- · 2020-01-24 21:34

Here is the solution in words.

Left shift an integer with initial value 1 n times and then do an AND with the original byte. If the result is non-zero, bit is Set otherwise not. :)

查看更多
登录 后发表回答