Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do an integer log2() in C++?

In the C++ standard libraries I found only a floating point log method. Now I use log to find the level of an index in a binary tree ( floor(2log(index)) ).

Code (C++):

int targetlevel = int(log(index)/log(2)); 

I am afraid that for some of the edge elements (the elements with value 2^n) log will return n-1.999999999999 instead of n.0. Is this fear correct? How can I modify my statement so that it always will return a correct answer?

like image 994
Peter Smit Avatar asked Jun 15 '09 05:06

Peter Smit


People also ask

How is log2 implemented?

How it works: The input integer x is casted to float and then reinterpret as bits. The IEEE float format stores the exponent in bits 30-23 as an integer with bias 127, so by shifting it 23 bits to the right and subtracting the bias, we get log2(x).

How do you write a log2 function in C++?

log2() function in C++ with Examples The function log2() of cmath header file in C++ is used to find the logarithmic value with base 2 of the passed argument. Parameters: This function takes a value x, in the range [0, ∞] whose log value is to be found.


1 Answers

If you are on a recent-ish x86 or x86-64 platform (and you probably are), use the bsr instruction which will return the position of the highest set bit in an unsigned integer. It turns out that this is exactly the same as log2(). Here is a short C or C++ function that invokes bsr using inline ASM:

#include <stdint.h> static inline uint32_t log2(const uint32_t x) {   uint32_t y;   asm ( "\tbsr %1, %0\n"       : "=r"(y)       : "r" (x)   );   return y; } 
like image 68
Matt J Avatar answered Oct 01 '22 03:10

Matt J