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);
}
You have an infinite loop because you never change the value of n. Instead of
n >> 1;
usen = n >> 1
.