2

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

  • Congratulations! You stumbled upon a little gem, here. Logarithm is an awesome function that can magically solve lots of complicated problems. For instance, it can magically transform a number into its number of bits; or magically transform a multiplication into an addition. – Stef Jan 07 '22 at 13:45
  • 1
    Note that the formula you gave is not exactly correct - it should be `total_bits=floor(log2(num))+1`. I guess they didn't need to explicitly write the `floor`, because this line was in a programming language that automatically did the casting to `int` by truncating the non-integer part. – Stef Jan 07 '22 at 13:46
  • If you're not comfortable with bits, think about digits instead, and replace log2 with log10. log10(100) = 2, and log10(1000) = 3, and every number between 100 and 999 has 3 digits. – Stef Jan 07 '22 at 13:48
  • See also [this answer to "Where can I learn about logarithms?"](https://stackoverflow.com/a/128678/3080723) and if you can get your hands on this book: [e: The story of a number](https://www.goodreads.com/book/show/271361.e) – Stef Jan 07 '22 at 13:53

2 Answers2

1

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.

Stef
  • 13,242
  • 2
  • 17
  • 28
0

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.

gnasher729
  • 51,477
  • 5
  • 75
  • 98
  • Rounding errors can be really fun, but I'd still be very surprised to encounter a `log2` function that doesn't return `16.0` on `log2(65536)`. – Stef Jan 07 '22 at 14:24