Reverse bit pattern in C

后端 未结 6 1584
猫巷女王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 05:53

    Pop bits off your input and push them onto your output. Multiplying and dividing by 2 are the push and pop operations. In pseudo-code:

    reverse_bits(x) {
        total = 0
        repeat n times {
           total = total * 2
           total += x % 2 // modulo operation
           x = x / 2
        }
        return total
    }
    

    See modulo operation on Wikipedia if you haven't seen this operator.

    Further points:

    • What would happen if you changed 2 to 4? Or to 10?
    • How does this effect the value of n? What is n?
    • How could you use bitwise operators (<<, >>, &) instead of divide and modulo? Would this make it faster?
    • Could we use a different algorithm to make it faster? Could lookup tables help?

提交回复
热议问题