View the Most Wanted LQ Wiki articles.
 Home Forums HCL Reviews Tutorials Articles Register Search Today's Posts Mark Forums Read
 LinuxQuestions.org How to calculate integer binary logarithm in C?
 Programming This forum is for all programming questions. The question does not have to be directly related to Linux and any language is fair game.

Notices

 11-27-2004, 02:50 AM #1 shy Member   Registered: Dec 2002 Location: Russia Distribution: ASP linux Posts: 94 Rep: How to calculate integer binary logarithm in C? Is it possible to calculate binary logarithm of integer value in C (assuming that only one bit is set) without any math functions? E.g. I need a function that maps 0001 -> 1 0010 -> 2 0100 -> 3 1000 -> 4 and so on, using simple bitwise operations (AND OR XOR NOT etc)
 11-27-2004, 07:43 AM #2 nukkel Member   Registered: Mar 2003 Location: Belgium Distribution: Hardened gentoo Posts: 323 Rep: you can do something like Code: ```int log2( int input ) { log = 1; if( input == 0 ) return 0; while( input != 1 ) { input >> 1; log++; } return log; }``` Basically it shifts the input to the right, one bit at a time, until the '1' bit is at the least significant position. The result will be wrong when the input contains more than one set bit!