2010-03-12 84 views
48

如何检查是否在一个字节的某一位被设置?检查是否有点设置或不

bool IsBitSet(Byte b,byte nPos) 
{ 
    return .....; 
} 
+0

你最后一段文字没有任何意义。 – leppie 2010-03-12 09:48:16

+9

这听起来像一个家庭作业的问题,但想太多的人是如何从这个代码snipset .. – Manjoor 2010-03-12 10:26:32

+1

我使用这个在我的工作得到中获益,挣扎是真的。 – cambunctious 2016-06-01 15:41:36

回答

116

听起来有点像功课,但:

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

POS 0是最显著位,POS 7是最多的。

+32

又一个班轮我总是谷歌,而不是仅仅学习它:) – grapkulec 2010-10-14 09:04:55

5

这是用文字解决的。

左移位的整数与初始值1 n倍,然后做一个并与原来的字节。如果结果不为零,则该位置1否则不是。 :)

+0

好的。 3的字节,测试是否设置了位1。所以1 << 1是2. 2&3是不正确的。失败。 – spender 2010-03-12 09:51:14

+1

@spender:ERR,肯定2和3是2(二进制10和11 = 10),其是非零的,并因此一个真正的结果。好的,C#不会让你像C/C++那样做,所以你需要一个!= 0测试。 – Skizz 2010-03-12 09:55:05

+0

也许检查应该是非零? afaik,非零不是真的。 – spender 2010-03-12 09:55:48

3

右Shift您输入的N位来与1面膜,然后测试你是否有0或1

+0

我更喜欢这种方式太绕,左移似乎只是那么不自然:) – leppie 2010-03-12 09:52:16

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]; 
} 
+5

如果你摆弄一点,你的表现后很可能。这样做可能会感觉更多的OO,但它会杀死perf。 – 2012-10-31 00:29:39

+0

我不会低估你或任何东西,但如果你正在寻找表现,那么你不应该这样做。 – Gaspa79 2016-11-03 18:13:52

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); 
    } 
2
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

对于解释您的解决方案,通常是一个很好的做法,更多的是为什么而不是如何。 – ForceMagic 2012-10-11 03:41:49

+0

OMG,让我们抛开问题编译器是否会precalc所有Math.Pow你,但为什么不这样做的((X Math.Pow)!= 0),而不是?它更清晰,可以节省几纳秒。 – Konstantin 2017-04-30 01:43:17

10

基于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; 
} 
0

相当于马里奥·F编码,但移动字节而不是掩码:

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