繁体   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