需要多少位? [英] How many bits are needed?
问题描述
在C ++中,什么是找出需要多少位来存储一个给定的int最快的方法是什么?
In C++, what's the fastest way to find out how many bits are needed to store a given int?
我可以尝试划分数与2很多次,但分歧是pretty的慢。有没有快速的方法?
I can try dividing the number with 2 many times but divisions are pretty slow. Is there any fast way?
编辑:非常感谢你的anwsers家伙。当我说一个int我的我的岗位,我的意思是任何4个字节的int。举例来说,如果我存储30665,我想作为一个结果15位。
推荐答案
您可以通过逐步打破一半的价值,以更快的缩小范围。
You can break the value progressively by halves to narrow it down faster.
int bits_needed(uint32_t value)
{
int bits = 0;
if (value >= 0x10000)
{
bits += 16;
value >>= 16;
}
if (value >= 0x100)
{
bits += 8;
value >>= 8;
}
if (value >= 0x10)
{
bits += 4;
value >>= 4;
}
if (value >= 0x4)
{
bits += 2;
value >>= 2;
}
if (value >= 0x2)
{
bits += 1;
value >>= 1;
}
return bits + value;
}
请参阅它在行动: http://ideone.com/1iH7hG
编辑:不好意思,原来的版本需要一个额外的任期。它现在是固定的。
Sorry, the original version needed one additional term. It's fixed now.
编辑2:作为在评论中提出的环形状
Edit 2: In loop form as suggested in the comments.
int bits_needed(uint32_t value)
{
int bits = 0;
for (int bit_test = 16; bit_test > 0; bit_test >>= 1)
{
if (value >> bit_test != 0)
{
bits += bit_test;
value >>= bit_test;
}
}
return bits + value;
}
此算法返回 0
为输入 0
,这意味着你不必在所有需要任何位恩 0
codeA值。如果你宁愿它返回 1
而不是,只是改变返回值位+ 1
。
This algorithm returns 0
for an input of 0
, meaning you don't need any bits at all to encode a value of 0
. If you'd rather it return 1
instead, just change the return value to bits + 1
.
这篇关于需要多少位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!