检查是否设置了位

Man*_*oor 53 .net c# bit-manipulation

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

bool IsBitSet(Byte b,byte nPos)
{
   return .....;
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*o F 139

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

bool IsBitSet(byte b, int pos)
{
   return (b & (1 << pos)) != 0;
}
Run Code Online (Sandbox Code Playgroud)

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

  • 另一个单行我总是谷歌而不是只是学习它:) (44认同)

Shi*_*mmy 11

根据Mario Fernandez的回答,我想为什么不把它放在我的工具箱中作为一种不仅限于数据类型的方便的扩展方法,所以我希望可以在这里分享它:

/// <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;
}
Run Code Online (Sandbox Code Playgroud)

  • 这是非常低效的。位操作非常快。调用此转换函数要慢几个数量级。备选方案:为不同的输入类型(如uint,byte,ulong)定义多个相同的函数。 (3认同)

Bri*_*vez 6

这也适用(在.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];
}
Run Code Online (Sandbox Code Playgroud)

  • 如果你有点摆弄,你可能会在表演之后.这样做可能会感觉更多OO,但它会杀死perf. (11认同)
  • 我不会贬低你或任何东西,但如果你正在寻找性能,那么你不应该这样做。 (4认同)

kaa*_*lus 6

等效于 Mario F 代码,但移动字节而不是掩码:

bool IsBitSet(byte b, int pos)
{
   return ((b >> pos) & 1) != 0;
}
Run Code Online (Sandbox Code Playgroud)


Aam*_*mir 5

这是单词的解决方案.

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


Mar*_*ers 5

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