Marishka33
Marishka33

Reputation: 21

Find leading 1s in the binary number

everyone,

I am new in C and I try to understand the work with bytes, binary numbers and another important thing for the beginner.

I hope someone can push me in the right direction here.

For example, I have a 32- bits number 11000000 10101000 00000101 0000000 (3232236800). I also assigned each part of this number to separate variables as a=11000000 (192), b = 10101000 (168), c =00000101 (5) d = 0000000 (0). I am not sure if I really need this.

Is there any way to find the last 1 in the number and use this location to calculate the number of leading 1s?

Thank you for help!

Upvotes: 0

Views: 1474

Answers (2)

Danny
Danny

Reputation: 114

Sorry I am not a C expert, but here's the Python code I came up with:

num_ones = 0
while integer > 0:
    if integer % 2 == 1:
        num_ones += 1
    else:
        num_ones = 0
    integer = integer >> 1

Basically, I count the number of continuous 1's by bit shifting the given integer. A zero would reset the counter.

Upvotes: 0

Yunnosch
Yunnosch

Reputation: 26703

You can determine the bitposition of the first leading 1 by this formula:

floor(ln(number)/ln(2))

Where "floor()" means rounding down.
For counting the number of consecutive leading ones (if I get the second part of your question correctly) I can only imagine a loop.

Note 1:
The formula is the math formula for "logarithm of number on the base of 2".
The same works with log10(). Basically you can use any logarithm (i.e. to any base) this way to adapt to a different base.

Note 2:
It is of course questionable whether this formula is more efficient than search from MSB downwards with a loop. It could be with good FPU support. It probably is not for 8bit values. Double check in case you are out to speed optimise.

Upvotes: 1

Related Questions