Convert 0x1234 to 0x11223344

前端 未结 13 984
我在风中等你
我在风中等你 2021-01-30 13:07

How do I expand the hexadecimal number 0x1234 to 0x11223344 in a high-performance way?

unsigned int c = 0x1234, b;
b = (c & 0xff) << 4 | c & 0xf |          


        
13条回答
  •  无人共我
    2021-01-30 13:21

    Here's another attempt, using eight operations:

    b = (((c & 0x0F0F) * 0x0101) & 0x00F000F) + 
        (((c & 0xF0F0) * 0x1010) & 0xF000F00);
    b += b * 0x10;
    
    printf("%x\n",b); //Shows '0x11223344'
    

    *Note, this post originally contained quite different code, based on Interleave bits by Binary Magic Numbers from Sean Anderson's bithacks page. But that wasn't quite what the OP was asking. so it has ben removed. The majority of the comments below refer to that missing version.

提交回复
热议问题