如何检查字节中的某个位是否已设置?
bool IsBitSet(Byte b,byte nPos)
{
return .....;
}
听起来有点像家庭作业,但是:
bool IsBitSet(byte b, int pos)
{
return (b & (1 << pos)) != 0;
}
pos 0是最低有效位,pos 7是最高位。
基于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;
}
这是单词的解决方案。
左移一个初始值为1 n次的整数,然后与原始字节进行AND运算。如果结果不为零,则位置位,否则不置位。 :)
这也适用(在.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];
}
右移你的输入n位并用1屏蔽,然后测试你是否有0或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;
相当于Mario F代码,但改变字节而不是掩码:
bool IsBitSet(byte b, int pos)
{
return ((b >> pos) & 1) != 0;
}
就像是
return ((0x1 << nPos) & b) != 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);
}