tags:

views:

435

answers:

4

Shhow me a very simple one line example in C# to check if a given bit is set in given byte

function signature should be like

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

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. :)

Aamir
spender
@spender: err, surely 2 and 3 is 2 (in binary 10 and 11 = 10) which is non-zero and therefore a true result. OK, C# doesn't let you do that like C/C++ does so you'd need a != 0 test.
Skizz
Perhaps the check should be for non-zero? afaik, non-zero ain't true.
spender
Yes the check should be for non-zero instead of true. My C++ background :)
Aamir
+4  A: 

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.

Mario
yet another one-liner I always google for instead of just learn it :)
grapkulec
+2  A: 

Right shift your input n bits down and mask with 1, then test whether you have 0 or 1.

Mark Byers
I prefer this way around too, left shifting just seems so unnatural :)
leppie
A: 

something like

return ((0x1 << nPos) & b) != 0

RedPaladin