C printing bits

前端 未结 5 1835
死守一世寂寞
死守一世寂寞 2020-12-03 15:14

I am trying to write a program in C that prints bits of int. for some reason i get wrong values,

void printBits(unsigned int num){
    unsigned int size = si         


        
5条回答
  •  失恋的感觉
    2020-12-03 15:29

    The result you get is because num&maxPow is either 0 or maxPow. To print 1 instead of maxPow, you could use printf("%u ", num&maxPow ? 1 : 0);. An alternative way to print the bits is

    while(maxPow){
        printf("%u ", num&maxPow ? 1 : 0);
        maxPow >>= 1;
    }
    

    i.e. shifting the bitmask right instead of num left. The loop ends when the set bit of the mask gets shifted out.

提交回复
热议问题