簡體   English   中英

如何獲得以32位整數為單位的長度

[英]How to get length in bits of 32-bit integer

我已經嘗試了JavaScript中的幾種變體,但沒有一種能獲得理想的結果。

 assert(countIntegerBits(4), 3) // 100 assert(countIntegerBits(8), 4) // 1000 assert(countIntegerBits(20), 5) // 10100 assert(countIntegerBits(100), 7) // 1100100 // https://stackoverflow.com/questions/43122082/efficiently-count-the-number-of-bits-in-an-integer-in-javascript function countIntegerBits(integer) { var length = 0 while (integer = Math.floor(integer)) { if (integer & 1) { length++ } integer /= 2 } return length } function countIntegerBits(integer) { // var length = 0 // while (integer !== 0) { // length += countIntegerBits32(integer | 0) // integer /= 0x100000000 // } // return length // // or perhaps this: // https://gist.github.com/everget/320499f197bc27901b90847bf9159164#counting-bits-in-a-32-bit-integer } function countIntegerBits32(integer) { integer = integer - ((integer >> 1) & 0x55555555) integer = (integer & 0x33333333) + ((integer >> 2) & 0x33333333) return ((integer + (integer >> 4) & 0xF0F0F0F) * 0x1010101) >> 24 } function countStringBits(string) { // looks like this / 8 would be good enough // https://codereview.stackexchange.com/questions/37512/count-byte-length-of-string var length = 0; for (var i = 0; i < normal_val.length; i++) { var c = normal_val.charCodeAt(i); length += c < (1 << 7) ? 1 : c < (1 << 11) ? 2 : c < (1 << 16) ? 3 : c < (1 << 21) ? 4 : c < (1 << 26) ? 5 : c < (1 << 31) ? 6 : Number.NaN } return length; } function countFloatBits(float) { // looks too complicated for an SO question // http://binary-system.base-conversion.ro/real-number-converted-from-decimal-system-to-32bit-single-precision-IEEE754-binary-floating-point.php?decimal_number_base_ten=1.23&sign=0&exponent=01111111&mantissa=00111010111000010100011 } function assert(a, b) { if (a !== b) throw new Error(a + ' != ' + b) } 

我要避免的是此轉換為字符串的黑客

var length = integer.toString(2).split('').length

我唯一想到的另一件事是檢查bit是否已設置 ,直到到達第一個1 ,然后從那里開始計數。

 assert(countIntegerBits(4), 3) // 100 assert(countIntegerBits(8), 4) // 1000 assert(countIntegerBits(20), 5) // 10100 assert(countIntegerBits(100), 7) // 1100100 function countIntegerBits(integer) { var i = 0 while (true) { if (integer & (1 << i)) { return 31 - i } i++ } } function assert(a, b) { if (a !== b) throw new Error(a + ' != ' + b) } 

但這似乎不太正確,因為我不確定所有整數是否都在后台表示為32位,例如, (4).toString(2)給出的是"100" ,而不是00000000000000000000000000000100 ,所以不確定。

在這里,我探討了如何以位為單位檢查字符串的長度,與浮點數相同,但是如果字符串是utf-8編碼,字符串看起來很簡單,但似乎浮點數是一件大事,所以我的問題只涉及整數直至JavaScript支持的最大值。 就目前的所有實際用途而言,我將只考慮不超過10億的整數,因此它不需要考慮123e456 bigints或其他任何東西,只需考慮不超過數十億或不超過32的基本整數, JavaScript中的最大位整數。

自然對數(好吧,記錄到任何基礎)和另一對基礎之間存在關系。 要獲取以2為底的日志:

const log2 = n => Math.log(n) / Math.log(2);

您想在添加1后四舍五入:

const bits = n => Math.floor(log2(n) + 1);

暫無
暫無

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

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