简体   繁体   English

如何计算O(1)中的二进制长度?

[英]How to count binary length in O(1)?

Normally, I have to convert an integer to binary in a std::string then use the method std::string::size() to get the length of the binary number. 通常,我必须在std :: string中将整数转换为二进制,然后使用std :: string :: size()方法获取二进制数的长度。

So 100 gives " 1100100 " (the length is 7 ) 因此100给出“ 1100100 ”(长度为7

But it is a O(n) algorithm (at least), and I am writing a performance-intensive program that requires lots of bit counting. 但这至少是一种O(n)算法,我正在编写一个性能密集型程序,该程序需要大量的位计数。 Is there any algorithm that lets we know the length of any given 'binary' number without having to convert the number to std::string beforehand in an instant? 是否有任何算法可以让我们知道任何给定“二进制”数字的长度,而无需立即将数字转换为std :: string? Thanks. 谢谢。

You are computing a binary logarithm. 您正在计算二进制对数。 There are a number of ways to do it, described on the bit twiddling hacks page . 有多种方法可以做到,请参阅hacks页面

One simple approach uses a look-up table. 一种简单的方法是使用查找表。 First, make a look-up table at start-up: 首先,在启动时制作一个查询表:

LogTable256[0] = LogTable256[1] = 0;
for (int i = 2; i != 256; i++) {
    LogTable256[i] = 1 + LogTable256[i / 2];
}
LogTable256[0] = -1; // if you want log(0) to return -1

Now you can use it as follows: 现在您可以按以下方式使用它:

if (tt = v >> 24) {
    r = 24 + LogTable256[tt];
} else if (tt = v >> 16) {
    r = 16 + LogTable256[tt];
} else if (tt = v >> 8) {
    r = 8 + LogTable256[tt];
} else {
    r = LogTable256[v];
}

这是我的一个答案,但这取决于您的计算机中如何实现log2()

length = ceil(log2(number))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM