Conversion of Decimal to Binary

Greetings, Coders!

How to calculate the minimum number of binary digits needed to represent a three digit hexadecimal value?
Lg(n)* +1 of the "actual value" of the hex number. I can't remember if you need a change of base for C's log functions or if it has an lg.

so lg (8) is 3. +1 is 4, and observe: 1000b is 8 base 10.
lg (7) is 2.something, so +1 makes it 3. 7 needs 3 bits. Etc.


*Lg is log base 2.

Last edited on
12 ?


lastchance, can you please how calculations in order to know where is the 12 coming from? Build on what jonnin said if necessary.
Well, hexadecimal F is 15 decimal or 1111 binary.
Biggest unsigned 3-digiter is FFF or 111111111111 (unless my finger slipped that's 12 1s).

I assume that the professional programmers can confirm that or blast my amateurish try.
There are ceil(log(a) / log(b)) digits in base b required to represent a distinct values. This is true because of the properties of positional number systems. (ceil is the least succeeding integer function.)

Consider the case where a is 16 and b is 2. Remember that 2 is the number of values that a single bit can take, and 16 is the number of values that a single hexadecimal digit (hexit) can take.

In this case, since ceil(log(a) / log(b)) = 4, exactly 4 bits are needed to represent one hexit.
Evidence:
0000 = 0 = 0
0001 = 1 = 1
...
1110 = 14 = E
1111 = 15 = F.
Given that your value contains three hexadecimal digits, there are ceil(log(16) / log(2)) * 3 = 12 bits required.

You can do that multiplication because of the property of logarithms:
Three hexadecimal digits can represent 16^3 distinct values, and given that (log(a) / log(b)) is an integer, you can drop the ceiling function:
ceil(log(a^3) / log(b)) = 3*log(a) / log(b) = 3 * 4 = 12;

@lastchance
I'm too slow ;)
Last edited on
Thank-you @mbozzi!
ah, I thought you meant on a per-value solution, like if the 3 digit hex were 1, you need 1 bit, and if it were 100 you need 7 bits, etc. Some sort of variable length approach computed on the fly, not just the answer for the biggest 3 digit hex.

remember that if its signed you need 1 more bit OR the max value of the hex is 1/2 the max of unsigned depending on how you see it.



Last edited on
Okay, thank you so much mbozzi and the rest for being so much helpful. I was totally lost! Now I understand fully.
Topic archived. No new replies allowed.