jalilweb.com

You are here: Home arrow University arrow how to calculate the number of bits in an integer
  • 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 (3)add comment

Steve said:

Hmmmm.... your comment handling doesn't work very well... no "special characters", which in the programming world is quite restrictive!

That should say "c plus plus", and the shift operators have all been removed or messed up.

Maybe quoting will work

// compile-time calculation of the number of bits an integer requires
template
struct num_bits
{
enum { value = 1 num_bits> 1)>::value };
};

template
struct num_bits // exit condition
{
enum { value = 0 };
};
August 06, 2010

Steve said:

if you're using c and want to calculate this for a constant value, here's a compile-time calculation:

template
struct num_bits
{
enum { value = 1 num_bits> 1)>::value };
};

template
struct num_bits // exit condition
{
enum { value = 0 };
};
August 06, 2010

Luca Deltodesco said:

Or perhaps:

int(log(x)/log(2)) 1
April 29, 2010

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 >