Visit Jeremy's Blog.
 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, 03: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, 08: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!

 Posting Rules You may not post new threads You may not post replies You may not post attachments You may not edit your posts BB code is On Smilies are On [IMG] code is Off HTML code is Off Forum Rules

 Similar Threads Thread Thread Starter Forum Replies Last Post epsharma Linux - Software 4 07-02-2006 11:45 AM psychobyte Linux - Hardware 1 08-11-2005 03:59 AM shahg_shahg Linux - Networking 1 01-17-2005 09:02 AM Ephracis Linux - General 1 12-16-2004 12:11 PM p_nanda2002 Linux - Software 4 11-01-2002 03:51 AM

LinuxQuestions.org

All times are GMT -5. The time now is 10:22 AM.

 Contact Us - Advertising Info - Rules - LQ Merchandise - Donations - Contributing Member - LQ Sitemap -