簡體   English   中英

位操作:檢測字節中是否設置了至少5位?

[英]Bit manipulation: detect if at least 5 bits in byte are set?

檢查二進制數中是否設置了最小位數的最佳方法是什么?

例如,我需要查看此序列中是否至少將5位設置為1:

101100010

我一直在尋找使用位掩碼之類的東西,但是對於如何做到這一點更加困惑。

任何幫助贊賞。

來自http://blog.faultylabs.com/2011.php?p=jsbitfun

/*
 popCnt(n)
 Returns the bit population count of n (that is: how many bits in n are set to 1)
 n must be an unsigned integer in the range [0..(2^32)-1]
 This lookup-table-free method is from Kernighan & Ritchie's "The C Programming Language"
 Exercise 2.9 (on page 62 of my copy). Not sure whether they (K&R) are the inventors.
*/
function popCnt(n) {
    n >>>= 0 /* force uint32 */
    for(var popcnt = 0; n; n &= n - 1) {
        popcnt++
    }
    return popcnt
}

有關其他算法的詳細信息,請參見http://en.wikipedia.org/wiki/Hamming_weight

如果您正在嘗試學習使用位,請使用位掩碼。

如果您需要一個非常簡單的解決方案,只需將整數轉換為其二進制值的字符串表示形式,並計算1的計數:

var i = 0x1 +0x4 + 0x8 +0x80; // 10001101 in binary
var numberOf1s = i.toString(2).split('1').length-1; // 4

總而言之,您只需要一行代碼即可:

if(<insert your var>.toString(2).split('1').length-1 >=5) {
  //At least 5 bits are set
}

首先使用位掩碼,尤其是在嘗試學習時。 將其視為一系列位時,這是最邏輯上最簡單的方法。 (現在有很多可以做聰明的把戲,但首先是第一和,與發動機無數像JS語言,實現可能使聰明,不那么聰明。)

為了測試是否設置了位b ,當input & (1 << b)非0時,它被設置,當然1 << b00000001 (0x01), 00000010 (0x02), 00000100 (0x04), 00001000 (0x08) )當b為0,1,2,3等等時,等等。 (注1是00000001以及<<如何將模式左移 b位)。

因此,對於每個0 <= b <8,查看該位是否已設置。 如果是,請將一個添加到計數器。

現在我們知道第一個八位字節中設置了多少位。

還要注意,我們關心的b只有一小組有限的值。 因此,我們可以消除循環並知道每個循環迭代的每個1 << b (像Firefox這樣的瀏覽器在單個表達式時可以非常快速地處理一系列逐位數學運算。)

快樂的編碼


為了好玩,我決定創建一個popCnt (和strCount )的快速性能測試用例,如其他答案所示,以及一個專門的位計數器fastCount8 ,它只使用數學運算而不會過於聰明。 simpleCount8如上所述。

假設fastCount8 (和simpleCount8 )都限制為單個八位字節(第一個字節),但對於這種特殊情況, fastCount8某些瀏覽器中速度要快得多。 (它在FF8中明顯更快,但在IE9中僅popCnt快一些,在Chrome 16中速度更慢 。)正如預期的那樣, strCountpopCnt慢得多,而simpleCount8則不popCnt

這是jsperf測試fastCount8

function fastCount8(n) {
    // >> has higher precedence than &
    return (n >> 0 & 1)
      + (n >> 1 & 1)
      + (n >> 2 & 1)
      + (n >> 3 & 1)
      + (n >> 4 & 1)
      + (n >> 5 & 1)
      + (n >> 6 & 1)
      + (n >> 7 & 1)
}

更新了lookup8lookupN (和一些變體), fastCount8NfastCount8N2 結果非常壯觀:FF8做了一些絕對驚人的數學優化,其他瀏覽器(我測試過)甚至無法接近保持給定的表達式。 此外,其他結果可能有點令人驚訝,並展示不同瀏覽器如何優化不同的東西......

...總而言之, lookup8lookupN2b在瀏覽器中看起來最一致......至少在給定的n范圍內。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM