2010-03-12 71 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; 
}