什么是计算以存储数所需要的比特的数量以最快的方式 [英] What is the fastest way to calculate the number of bits needed to store a number

查看:312
本文介绍了什么是计算以存储数所需要的比特的数量以最快的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想优化的一些位打包和拆包程序。为了做包装我需要计算存储整数值所需要的比特的数目。这是当前code。

 如果(N == -1)返回32;
如果(N == 0)返回1;
INT R = 0;
而(N)
{
    ++ R;
    N'GT;> = 1;
}
返回ř;


解决方案

您正在寻找确定一个数(L =最高位集)的整数日志基地2。肖恩·安德森的位操作黑客页面有多种方法,从在一个循环中明显计数位使用查表的版本。请注意,大多数的演示方法将需要修改的位与64位整数的工作,如果那样的便携性对你很重要。

只要确保任何你使用制定出的最高位设置需要换挡因为编译器实现要在一个无符号版本号做过'可能或可能不会签署延长>方式>经签署的价值操作

I'm trying to optimize some bit packing and unpacking routines. In order to do the packing I need to calculate the number of bits needed to store integer values. Here is the current code.

if (n == -1) return 32;
if (n == 0) return 1;
int r = 0;
while (n)
{
    ++r;
    n >>= 1;
}
return r;

解决方案

You're looking to determine the integer log base 2 of a number (the l=highest bit set). Sean Anderson's "Bit Twiddling Hacks" page has several methods ranging from the obvious counting bits in a loop to versions that use table lookup. Note that most of the methods demonstrated will need to be modified a bit to work with 64-bit ints if that kind of portability is important to you.

Just make sure that any shifting you're using to work out the highest bit set needs to be done' on an unsigned version of the number since a compiler implementation might or might not sign extend the >> operation on a signed value.

这篇关于什么是计算以存储数所需要的比特的数量以最快的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆