检查是否设置了位

问题描述 投票:51回答:9

如何检查字节中的某个位是否已设置?

bool IsBitSet(Byte b,byte nPos)
{
   return .....;
}
c# .net bit-manipulation
9个回答
132
投票

听起来有点像家庭作业,但是:

bool IsBitSet(byte b, int pos)
{
   return (b & (1 << pos)) != 0;
}

pos 0是最低有效位,pos 7是最高位。


11
投票

基于Mario Fernandez's answer,我想为什么不在我的工具箱中将它作为一种不仅限于数据类型的方便的扩展方法,所以我希望在这里分享它是可以的:

/// <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;
}

5
投票

这是单词的解决方案。

左移一个初始值为1 n次的整数,然后与原始字节进行AND运算。如果结果不为零,则位置位,否则不置位。 :)


5
投票

这也适用(在.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];
}

4
投票

右移你的输入n位并用1屏蔽,然后测试你是否有0或1。


1
投票
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;

1
投票

相当于Mario F代码,但改变字节而不是掩码:

bool IsBitSet(byte b, int pos)
{
   return ((b >> pos) & 1) != 0;
}

0
投票

就像是

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

0
投票

要检查16位字中的位:

  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);
  }
© www.soinside.com 2019 - 2024. All rights reserved.