Reverse bit pattern in C

后端 未结 6 1610
猫巷女王i
猫巷女王i 2021-01-05 05:16

I am converting a number to binary and have to use putchar to output each number.

The problem is that I am getting the order in reverse.

Is the

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-05 06:09

    Let me guess: you have a loop that prints the 0th bit (n&1), then shifts the number right. Instead, write a loop that prints the 31st bit (n&0x80000000) and shifts the number left. Before you do that loop, do another loop that shifts the number left until the 31st bit is 1; unless you do that, you'll get leading zeros.

    Reversing is possible, too. Somthing like this:

    unsigned int n = 12345; //Source
    unsigned int m = 0; //Destination
    int i;
    for(i=0;i<32;i++)
    {
        m |= n&1;
        m <<= 1;
        n >>= 1;
    }
    

提交回复
热议问题