简体   繁体   中英

Bitwise shift makes my program halt?

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; use n = n >> 1 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM