2

I am working with an assignment where I have to write a C function that calculates log2 of an unsigned integer n by finding the most significant set bit and returning the position of that bit. For example, if n is 17 (0b10001), the function should return 4.

Below is the code I have so far, but the bitwise operation makes the program halt. By commenting out the loop through line 6-9 the program works fine. I cannot for the life of me understand why it does that. Can someone help me?

#include<stdio.h>
#include<stdlib.h>

int mylog2(unsigned int n) {
    int log = 1;
    while (n != 1) {
        n >> 1;
        log++;
    }
    return log;
}


int main() {
    int a;
    a = mylog2(17);
    printf("%d", a);
    getch();
    return(0);
}
  • 7
    `n >> 1;` -> `n >>= 1;` – Mysticial Sep 16 '12 at 18:25
  • The fact that your program halts might be a problem, but it's not the halting problem. – sepp2k Sep 16 '12 at 18:26
  • 1
    +1 @Mysticial. And user167037, if you turn on some more warnings, you'll probably get something about "result of expression unused" for your original program. `clang` warns by default, even. – Carl Norum Sep 16 '12 at 18:26
  • Yup, I edited that to "halt" instead now. – user1676037 Sep 16 '12 at 18:27
  • There are many much faster ways to get log₂n in [here](http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogIEEE64Float). And your CPU is also highly likely to have a single instruction to do that. Check your compiler's intrinsic list – phuclv May 31 '19 at 04:25

2 Answers2

3

You have an infinite loop because you never change the value of n. Instead of n >> 1; use n = n >> 1.

Musa
  • 96,336
  • 17
  • 118
  • 137
1

Look in your while loop. You do n >> 1 but you never assign it.

Robert Kühne
  • 898
  • 1
  • 12
  • 33