Bitwise shift makes my program halt?

288 Views Asked by At

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);
}
2

There are 2 best solutions below

0
On

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

0
On

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