LinuxQuestions.org
View the Most Wanted LQ Wiki articles.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
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

Reply
 
Search this Thread
Old 11-27-2004, 02:50 AM   #1
shy
Member
 
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, 07:43 AM   #2
nukkel
Member
 
Registered: Mar 2003
Location: Belgium
Distribution: Hardened gentoo
Posts: 323

Rep: Reputation: 30
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!
 
  


Reply


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 10:45 AM
How to calculate Server power needs psychobyte Linux - Hardware 1 08-11-2005 02:59 AM
calculate (in & out) traffic shahg_shahg Linux - Networking 1 01-17-2005 08:02 AM
Calculate in shell script Ephracis Linux - General 1 12-16-2004 11:11 AM
calculate traffic using iptables p_nanda2002 Linux - Software 4 11-01-2002 02:51 AM


All times are GMT -5. The time now is 09:07 AM.

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