Hi.
I'm looking for some exercises to prepare myself for an exam in basic c programming.
I've found one now that seems like a good one:
The binary logarithm of n (log2n) is the power to which the number 2 to must be raised to obtain the value n. Write a C function that calculates log2 of an unsigned integer n using the following approach: find the most significant set bit in n and return the position of this bit. For example, if n is 17 (0b10001), the function should return 4.
To solve this problem you need to read up on how to express logical and bitwise shift operations in C.
Here's my attempt:
First, I'm thinking I have to count the input (scanf) number's bits, and print that number. What I mean by this is the following:
If the input number is 22, the binary number is 0b11000. If I count those numbers, I end up with 5. But since the first position starts with 0, I should get 5-1 = 4.
Can you guide me somehow on how to solve this? I'm familiar with shift operations (22 >> 2 = 0b110) but my knowledge is very limited.