Checking if a bit is set or not
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. :)
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;
}
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.