|
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.
|