How would you do that in C? (Example: 10110001 becomes 10001101 if we had to mirror 8 bits). Are there any instructions on certain processors that would simplify this task?
Given a signed 32-bit integer x , return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1] , then return 0 . Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Repeating the same permutation twice returns to the original ordering on the items, so the bit reversal permutation is an involution. This permutation can be applied to any sequence in linear time while performing only simple index calculations.
Bitwise complement operator is used to reverse the bits of an expression.
Reverse Bits in C++ answer := answer OR (n AND i), and shift it to the left i times. n := n after right shifting 1 bit.
If you are interested in a more embedded approach, when I worked with an armv7a
system, I found the RBIT
command.
So within a C function using GNU extended asm
I could use:
uint32_t bit_reverse32(uint32_t inp32)
{
uint32_t out = 0;
asm("RBIT %0, %1" : "=r" (out) : "r" (inp32));
return out;
}
There are compilers which expose intrinsic C wrappers like this. (armcc __rbit
) and gcc
also has some intrinsic via ACLE but with gcc-arm-linux-gnueabihf
I could not find __rbit
C so I came up with the upper code.
I didn't look, but I suppose on other platforms you could create similar solutions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With