回答
聽起來有點像功課,但:
bool IsBitSet(byte b, int pos)
{
return (b & (1 << pos)) != 0;
}
POS 0是最顯著位,POS 7是最多的。
又一個班輪我總是谷歌,而不是僅僅學習它:) – grapkulec 2010-10-14 09:04:55
這是用文字解決的。
左移位的整數與初始值1 n倍,然後做一個並與原來的字節。如果結果不爲零,則該位置1否則不是。 :)
像
return ((0x1 << nPos) & b) != 0
這也適用(.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];
}
如果你擺弄一點,你的表現後很可能。這樣做可能會感覺更多的OO,但它會殺死perf。 – 2012-10-31 00:29:39
我不會低估你或任何東西,但如果你正在尋找表現,那麼你不應該這樣做。 – Gaspa79 2016-11-03 18:13:52
要檢查位在一個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);
}
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;
對於解釋您的解決方案,通常是一個很好的做法,更多的是爲什麼而不是如何。 – ForceMagic 2012-10-11 03:41:49
OMG,讓我們拋開問題編譯器是否會precalc所有Math.Pow你,但爲什麼不這樣做的((X Math.Pow)!= 0),而不是?它更清晰,可以節省幾納秒。 – Konstantin 2017-04-30 01:43:17
基於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;
}
相當於馬里奧·F編碼,但移動字節而不是掩碼:
bool IsBitSet(byte b, int pos)
{
return ((b >> pos) & 1) != 0;
}
- 1. 檢查是否有設置PHP
- 2. 檢查localStorage是否設置
- 3. 檢查cookie是否設置
- 4. 檢查節點是否有
- 5. 檢查變量是否被設置或不「全局」的功能
- 6. 如何檢查是否兩個PHP會話設置或不
- 7. 檢查是否有cookie設置,如果不是輸出腳本
- 8. MongoEngine - 查詢 - 如何檢查ListField是否爲空或未設置
- 9. 檢查是否有類,並檢查是否被點擊
- 10. PHP檢查所有輸入是否設置不起作用?
- 11. 如何檢查aspnet配置文件變量是否設置或不?
- 12. 如何檢查cookie是否設置?
- 13. 檢查GET變量是否已設置
- 14. 檢查變量是否設置
- 15. HTACCESS檢查是否設置語言
- 16. Javascript檢查是否設置了陣列
- 17. PHP檢查用戶名是否設置
- 18. 如何檢查是否datatable.PrimaryKey設置
- 19. 檢查函數參數是否設置
- 20. cakephp - 檢查會話是否設置
- 21. 檢查cookie是否設置爲javascript
- 22. PHP檢查變量是否設置
- 23. 檢查JSP片段是否已設置
- 24. Liquibase:檢查是否設置了屬性
- 25. 檢查cookie是否設置時出錯
- 26. 如何檢查WaitHandle是否已設置?
- 27. 如何檢查LogWriter是否已設置?
- 28. 檢查變量是否設置爲NO_VALUE
- 29. Apache RewriteCondition:檢查屬性是否設置
- 30. 我如何檢查會話是否設置或不是從標題視圖
你最後一段文字沒有任何意義。 – leppie 2010-03-12 09:48:16
這聽起來像一個家庭作業的問題,但想太多的人是如何從這個代碼snipset .. – Manjoor 2010-03-12 10:26:32
我使用這個在我的工作得到中獲益,掙扎是真的。 – cambunctious 2016-06-01 15:41:36