How can I shuffle bits efficiently?

前端 未结 7 1181
闹比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

    your answer to the even and odd bits shuffle for 64 bits is not accurate. To extend the 16 bit solution to 64 bit solution, we need not only to extend the masks, but also cover the swapping interval from 1 all the way to 16:

    x = bit_permute_step(x, 0x2222222222222222, 1);
    x = bit_permute_step(x, 0x0c0c0c0c0c0c0c0c, 2);
    x = bit_permute_step(x, 0x00f000f000f000f0, 4);
    **x = bit_permute_step(x, 0x0000ff000000ff00, 8);
    x = bit_permute_step(x, 0x00000000ffff0000, 16);**
    

提交回复
热议问题