Originally Posted by

**Chris87**
Hello, I'm looking for a function that takes an unsigned number and returns the number of binary digits needed to represent the number in binary.

For example, the number 36 is 100100 in binary (or is it 001001?) and thus has 6 digits. Hence, the function I'm looking for takes 36 as an argument and returns 6.

Also, suppose the function/macro is called DIGIT_FIND, is the following legal C code?

Code:

unsigned max_value_of_36: DIGIT_FIND(36);

Not a quick fix perhaps, but remember what a number base does for digits. In base 10 (the normal base), this:

10101, means that, from right to left, we have 1 one, 0 * base (10), 1 * base * base (10^2nd), 0 * base * base * base (10^3rd), and 1 * base * base * base * base. (10^4th)

Adding it all up then we get:

Code:

1
0
100
10000
=====
10,101 Total

You see the obvious pattern here. It works the very same way for binary (base 2) numbers: 1 == 1, 10 == 1 * base (2), 100 == 1 * base * base (1 * 2^2nd), etc.

So knowing the above, and using the mod (remainder) math operator in C "%", writing up such function becomes a simple loop (either a while, or a for loop will work splendidly).

Now, let's see you come up with a try in code. You'll learn a lot more by doing it, than by merely seeing how someone else does it, for sure.