Reverse integer bitwise without using loop

前端 未结 5 2123
孤独总比滥情好
孤独总比滥情好 2021-02-10 01:39

I want to write a program which reverses the bits of an integer.
Ex 11000101 to 10100011
I know how to solve this using a loop, but I came across solutions that do it us

5条回答
  •  醉梦人生
    2021-02-10 02:20

    As mentioned, it's not reversing the bits, just the nibbles. But you can decompose a real bit-reversal to something like that as well, like this (not tested):

    // swap nibbles
    x = x >> 4 | x << 4;
    // swap groups of 2
    x = (x >> 2) & 0x33 | (x & 0x33) << 2;
    // swap groups of 1
    x = (x >> 1) & 0x55 | (x & 0x55) << 1;
    

    You can of course extend that pattern to reverse a wider number. Every additional step doubles the width of the number it reverses, which makes this method far more scalable than moving every bit to its position one by one. To reverse a 64bit number, this algorithm takes only 6 "steps" (at 5 operations for all but 1 step, so roughly 30 operations) whereas the bit-by-bit algorithm takes 64 steps (at 3 operations per step except one, so 191 operations).

    You can reorder the steps, if you want.

提交回复
热议问题