# Bitflags inquiry

Printable View

• 01-03-2009
Chris87
Bitflags inquiry
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);`
• 01-03-2009
zacs7
> Also, suppose the function/macro is called DIGIT_FIND, is the following legal C code?
Nope. But remove the collon, replace it with an equals and it might be.

Just find the most significant non-zero bit and that will tell you how many binary digits you need to represent the number, ie work from the msb to the lsb. This website has a tutorial on bitwise operators you might want to check out.
• 01-03-2009
tabstop
No, it's not legal code, as this is not one of the situations where : is meaningful.

And I would suggest learning about either logarithms or bitshifting.
• 01-03-2009
MK27
I think it is 100100. I doubt there is a function to do this since it probably doesn't have any practical application, but it shouldn't be hard to write one.
• 01-03-2009
Adak
Quote:

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.