Is there a built-in function to reverse bit order

后端 未结 8 1360
情书的邮戳
情书的邮戳 2020-12-13 00:34

I\'ve come up with several manual ways of doing this, but i keep wondering if there is something built-in .NET that does this.

Basically, i want to reverse the bit o

8条回答
  •  长情又很酷
    2020-12-13 01:02

    You can find bit twiddling algorithms in the fxtbook. Chapter 1.14 gives these bit swapping algorithms:

        static uint bitSwap1(uint x) {
            uint m = 0x55555555;
            return ((x & m) << 1) | ((x & (~m)) >> 1);
        }
        static uint bitSwap2(uint x) {
            uint m = 0x33333333;
            return ((x & m) << 2) | ((x & (~m)) >> 2);
        }
        static uint bitSwap4(uint x) {
            uint m = 0x0f0f0f0f;
            return ((x & m) << 4) | ((x & (~m)) >> 4);
        }
    

    Which makes your byte value bit reversal:

        public static byte swapBits(byte value) {
            return (byte)(bitSwap4(bitSwap2(bitSwap1(value))));
        }
    

    The x86 JIT compiler doesn't do a great job optimizing this code. If speed matters then you could use it to initialize a byte[] to make it a fast lookup instead.

提交回复
热议问题