JavaScript函数检查对数字进行编码需要多少位? [英] JavaScript function to check how many bits are required to encode a number?
问题描述
我有以下问题.这是示例输入/输出数据:
I have the following problem. Here is sample input/output data:
- i:0,o:1(0)
- i:1,o:1(1)
- i:2,o:2(10)
- i:3,o:2(11)
- i:4,o:3(100)
- i:5,o:3(101)
- i:6,o:3(110)
- i:7,o:3(111)
但是,这只是使用最少的位数对数字进行编码.我想要一些与众不同的东西,很难把头缠在它上面.我希望输出为2的幂.
However, that is just using the smallest number of bits to encode the number. I want something slightly different, having a hard time wrapping my head around it. I want the output to be a power of 2.
- i:0,o:2(00)
- i:1,o:2(01)
- i:2,o:2(10)
- i:3,o:2(11)
- i:4,o:4(0100)
- i:5,o:4(0101)
- i:6,o:4(0110)
- i:7,o:4(0111)
- i:8,o:4(1000)
- ...
- i .... o:8
- ...
- i .... o:16
- ...
- i: 0, o: 2 (00)
- i: 1, o: 2 (01)
- i: 2, o: 2 (10)
- i: 3, o: 2 (11)
- i: 4, o: 4 (0100)
- i: 5, o: 4 (0101)
- i: 6, o: 4 (0110)
- i: 7, o: 4 (0111)
- i: 8, o: 4 (1000)
- ...
- i.... o: 8
- ...
- i.... o: 16
- ...
我该如何编写一个函数,该函数在JavaScript中使用一个整数,并返回给我o
以获取该数字?一种有效地执行此操作,并且不将其转换为字符串并使用随机JS帮助器功能的方法:)
How do I write a function that takes an integer in JavaScript, and returns to me o
for that number? One that is doing it efficiently and not converting things to strings and using random JS helper functions :)
推荐答案
如果您有点摆弄,可以找到位置MSb ",然后找到下一个2的幂(对于小于2的两个值,有例外情况)
If you're into bit fiddling, you could find the position of the MSB then find the next power of 2 (with an exceptional case for the two values below 2).
我们还可以找到一个封闭的表格:
We can also find a closed form:
const bits = x => Math.floor(1+Math.log2(x))
const npot = x => Math.pow(2, Math.ceil(Math.log2(x)))
const f = x => x < 2 ? 2 : npot(bits(x))
但是,鉴于范围内只有2的幂,因此仅使用条件阶梯会更容易,更快捷:
However, given the small number of powers of two in range, it's much easier and faster to just use a condition ladder:
const f = x => {
if (x < 2**2) return 2;
if (x < 2**4) return 4;
if (x < 2**8) return 8;
if (x < 2**16) return 16;
if (x < 2**32) return 32;
return 64;
}
(使用bigints时,为此使用循环...)
(When working with bigints, use a loop for that…)
这篇关于JavaScript函数检查对数字进行编码需要多少位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!