How can I shuffle bits efficiently?

前端 未结 7 1229
闹比i
闹比i 2020-12-29 06:15

I need to shuffle a 16 bit unsigned integer in a way that the even indexes land in the lower byte, and the odd indexes land in the upper byte.

input:
fedcba9         


        
7条回答
  •  鱼传尺愫
    2020-12-29 06:40

    In favour of being short:

    unsigned short segregate(unsigned short x)
    {
        x = (x & 0x9999) | (x >> 1 & 0x2222) | (x << 1 & 0x4444);
        x = (x & 0xC3C3) | (x >> 2 & 0x0C0C) | (x << 2 & 0x3030);
        x = (x & 0xF00F) | (x >> 4 & 0x00F0) | (x << 4 & 0x0F00);
        return x;
    }
    

提交回复
热议问题