Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mirror bits of a 32 bit word

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?

like image 543
Thomas Avatar asked Nov 22 '10 13:11

Thomas


People also ask

How do you reverse a 32 bit integer?

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).

How do you reverse a bit?

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.

Which operator is used to reverse the bits?

Bitwise complement operator is used to reverse the bits of an expression.

How do I reverse a bit of a number in CPP?

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.


1 Answers

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.

like image 196
lnksz Avatar answered Oct 04 '22 21:10

lnksz