Reverse bit pattern in C

后端 未结 6 1586
猫巷女王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:04

    I know: that is not exactly C, but I think that is an interesting answer:

    int reverse(int i) {
      int output;
      __asm__(
         "nextbit:"
            "rcll $1, %%eax;"
            "rcrl $1, %%ebx;"
            "loop nextbit;"
            : "=b" (output)
            : "a" (i), "c" (sizeof(i)*8) );
      return output;
    }
    

    The rcl opcode puts the shifted out bit in the carry flag, then rcr recovers that bit to another register in the reverse order.

提交回复
热议问题