How can I shuffle bits efficiently?

前端 未结 7 1180
闹比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:56

    The table approach shown by others is the most portable version and is probably quite fast.

    If you want to take advantage of special instruction sets there are some other options as well. For Intel Haswell and later for example the following approach can be used (requires the BMI2 instruction set extension):

    unsigned segregate_bmi (unsigned arg)
    {
      unsigned oddBits  = _pext_u32(arg,0x5555);
      unsigned evenBits = _pext_u32(arg,0xaaaa);
      return (oddBits | (evenBits << 8));
    }
    
    0 讨论(0)
提交回复
热议问题