University
how to calculate the number of bits in an integer 


| how to calculate the number of bits in an integer |
|
|
| 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){
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.
Bookmark
Email This
Comments (3)
![]()
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 |
|
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 }; }; |
| Next > |
|---|