How to check if a certain bit in a byte is set?
bool IsBitSet(Byte b,byte nPos)
{
return .....;
}
Whenever we calculate the binary number of an integer value then it is formed as the combination of 0's and 1's. So, the digit 1 is known as set bit in the terms of the computer.
Bitwise AND operation is used to check whether a particular bit is on or off.
9) Which statement is suitable to check 3rd (count from 0) bit is high (set) or not? The value of (1<<3) is 8 in Decimal and value of 0x08 is 8 in Decimal, both statements are suitable to check whether 3rd bit of num is High (set) or not.
Member functions Tests whether all bits from bitset are set or not.
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.
Based on Mario Fernandez's answer, I thought why not have it in my toolbox as a handy extension method not limited to datatype, so I hope it's OK to share it here:
/// <summary> /// Returns whether the bit at the specified position is set. /// </summary> /// <typeparam name="T">Any integer type.</typeparam> /// <param name="t">The value to check.</param> /// <param name="pos"> /// The position of the bit to check, 0 refers to the least significant bit. /// </param> /// <returns>true if the specified bit is on, otherwise false.</returns> public static bool IsBitSet<T>(this T t, int pos) where T : struct, IConvertible { var value = t.ToInt64(CultureInfo.CurrentCulture); return (value & (1 << pos)) != 0; }
Note: Do not use for performance critical operations, as this method always converts to long
.
Equivalent to Mario F code, but shifting the byte instead of mask:
bool IsBitSet(byte b, int pos)
{
return ((b >> pos) & 1) != 0;
}
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. :)
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];
}
Right shift your input n bits down and mask with 1, then test whether you have 0 or 1.
something like
return ((0x1 << nPos) & b) != 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With