Visit Jeremy's Blog.
Go Back > Forums > Non-*NIX Forums > Programming
User Name
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.


  Search this Thread
Old 11-27-2004, 03:50 AM   #1
Registered: Dec 2002
Location: Russia
Distribution: ASP linux
Posts: 94

Rep: Reputation: 15
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)
Old 11-27-2004, 08:43 AM   #2
Registered: Mar 2003
Location: Belgium
Distribution: Hardened gentoo
Posts: 323

Rep: Reputation: 30
you can do something like

int log2( int input ) {
    log = 1;

    if( input == 0 )
        return 0;
    while( input != 1 ) {
        input >> 1;

    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!


Thread Tools Search this Thread
Search this Thread:

Advanced Search

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

Similar Threads
Thread Thread Starter Forum Replies Last Post
How to calculate bandwidth on linux epsharma Linux - Software 4 07-02-2006 11:45 AM
How to calculate Server power needs psychobyte Linux - Hardware 1 08-11-2005 03:59 AM
calculate (in & out) traffic shahg_shahg Linux - Networking 1 01-17-2005 09:02 AM
Calculate in shell script Ephracis Linux - General 1 12-16-2004 12:11 PM
calculate traffic using iptables p_nanda2002 Linux - Software 4 11-01-2002 03:51 AM > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 10:00 PM.

Main Menu
Write for LQ is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration