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是最高位.
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)
这也适用(在.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)
等效于 Mario F 代码,但移动字节而不是掩码:
bool IsBitSet(byte b, int pos)
{
return ((b >> pos) & 1) != 0;
}
Run Code Online (Sandbox Code Playgroud)