jalilweb.com

You are here: Home
  • Decrease font size
  • Default font size
  • Increase font size
how to calculate the number of bits in an integer Print E-mail
Written by Jalil   
Tuesday, 02 June 2009

if you want to know the number of bits constituting an integer look no further. Here is a very simple solution.

int get_number_of_bits(int the_number){
           int bits = 1;
           int div = (the_number/2);
           while(div != 0){
                      bits++;
                      div = div/2;
           }
           return bits;
}

 

So this is just a simple division by 2 loop, that counts the number of times we could divide the number by two without the result being less than 1 (which is the number of bits -1).

This works for positive integers from 0 and up.

 

Now if you wanted to know the number of bits required to represent a number of elements (i.e. you want to know how many bits would represent a number of states, elements or anything you like)

then use the same algorithm above, except that you need to change the line:  int div = the_number/2   into int div = (the_number-1)/2

this is because, number of states or elements is never 0.

 

Feedback is very welcome.

 

 

Comments (0)add comment

Write comment
quote
bold
italicize
underline
strike
url
image
quote
quote
smile
wink
laugh
grin
angry
sad
shocked
cool
tongue
kiss
cry
smaller | bigger

busy
Last Updated ( Tuesday, 02 June 2009 )
 
Next >