C#, 63 45 31 bytes
Saved 18 bytes, thanks to Loovjo, and TuukkaX
Saved 14 bytes, thanks to Grax
b=>1+(int)System.Math.Log(b,2);
It uses, that a decimal number n has ⌊log2(n)⌋+1 bits, which is described on this page:
Number of Bits in a Specific Decimal Integer
A positive integer n has b bits when 2^(b-1) ≤ n ≤ 2^b – 1. For example:
- 29 has 5 bits because 16 ≤ 29 ≤ 31, or 2^4 ≤ 29 ≤ 2^5 – 1
- 123 has 7 bits
because 64 ≤ 123 ≤ 127, or 2^6 ≤ 123 ≤ 2^7 – 1
- 967 has 10 bits because
512 ≤ 967 ≤ 1023, or 2^9 ≤ 967 ≤ 2^10 – 1
For larger numbers, you could
consult a table of powers of two to find the consecutive powers that
contain your number.
To see why this works, think of the binary representations of the
integers 2^4 through 2^5 – 1, for example. They are 10000 through 11111,
all possible 5-bit values.
Using Logarithms
The above method can be stated another way: the number of bits is the
exponent of the smallest power of two greater than your number. You
can state that mathematically as:
bspec = ⌊log2(n)⌋ + 1
That formula has three parts:
log2(n) means the logarithm in base 2 of n, which is the exponent to
which 2 is raised to get n. For example, log2(123) ≈ 6.9425145. The
presence of a fractional part means n is between powers of two.
⌊x⌋ is the floor of x, which is the integer part of x. For example,
⌊6.9425145⌋ = 6. You can think of ⌊log2(n)⌋ as the exponent of the
highest power of two in the binary representation of n.
+1 takes the exponent to the next higher power of two. You can think of this step as accounting for the 2^0th place of your binary number,
which then gives you its total number of bits. For our example, that’s
6 + 1 = 7. You might be tempted to use the ceiling function — ⌈x⌉,
which is the smallest integer greater than or equal to x — to compute
the number of bits as such:
bspec = ⌈log2(n)⌉
However, this fails when n is a power of two.
floor(log2(num))+1– Kritixi Lithos 2 days agonumis a power of two. – Brian J 2 days ago