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:35

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;
}
查看更多
劳资没心,怎么记你
3楼-- · 2020-01-24 21:42

To check the bits in a 16-bit word:

  Int16 WordVal = 16;
  for (int i = 0; i < 15; i++)
  {
     bitVal = (short) ((WordVal >> i) & 0x1);
     sL = String.Format("Bit #{0:d} = {1:d}", i, bitVal);
     Console.WriteLine(sL);
  }
查看更多
淡お忘
4楼-- · 2020-01-24 21:48

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

查看更多
登录 后发表回答