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
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:
<<
, >>
, &
) instead of divide and modulo? Would this make it faster?