公告
财富商城
积分规则
提问
发文
2020-01-24 20:43发布
forever°为你锁心
How to check if a certain bit in a byte is set?
bool IsBitSet(Byte b,byte nPos) { return .....; }
Equivalent to Mario F code, but shifting the byte instead of mask:
bool IsBitSet(byte b, int pos) { return ((b >> pos) & 1) != 0; }
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;
something like
return ((0x1 << nPos) & b) != 0
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.
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]; }
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. :)
最多设置5个标签!
Equivalent to Mario F code, but shifting the byte instead of mask:
something like
sounds a bit like homework, but:
pos 0 is least significant bit, pos 7 is most.
This also works (tested in .NET 4):
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. :)