There are many solutions to count the total no. of bits of a number and below is one of them:-
int total_bits=log2(num)+1;
Can you explain, what's the use of log2(num) and adding 1?
Thanks & Regards
There are many solutions to count the total no. of bits of a number and below is one of them:-
int total_bits=log2(num)+1;
Can you explain, what's the use of log2(num) and adding 1?
Thanks & Regards
Let n
be a positive integer. Let k
be its number of bits.
Then n
and k
are linked by this mathematical relation:
2^(k-1) ≤ n < 2^k
Where ^
represents exponentiation.
Now, logarithm is a strictly increasing function, so this relation is equivalent to:
log2(2^(k-1)) ≤ log2(n) < log2(2^k)
And since log2
is exactly the inverse function of 2^...
, this is the same as:
k-1 ≤ log2(n) < k
Or equivalently:
k ≤ log2(n) + 1 < k+1
In other words, the integer k
is the integer part of log2(n) + 1
. We can write this as:
k = floor(log2(n) + 1)
Or in language C:
int k = log2(n) + 1;
Note: In this answer, I used ^
to represent exponentiation. In most programming languages, ^
represents bitwise-xor, which is completely unrelated to exponents. Be careful and avoid using ^
for exponents in your programs.
This doesn't count the number of bits, but it may or may not return the index of the highest bit that is set.
"May or may not" because of rounding errors: First, log2(65536) might not return 16, but 15.999999999999999999999 in which case you get the wrong answer. Second, if you need this for 64 bit numbers, then I can guarantee that either log2(0x8000_0000_0000_0000) or log2(0x7fff_ffff_ffff_ffff) will give the wrong result.