Convert 0x1234 to 0x11223344

前端 未结 13 962
我在风中等你
我在风中等你 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:34

    Assuming that, you want to always convert 0xWXYZ to 0xWWXXYYZZ, I believe that below solution would be little faster than the one you suggested:

    unsigned int c = 0x1234;     
    unsigned int b = (c & 0xf) | ((c & 0xf0) << 4) |
                     ((c & 0xf00) << 8) | ((c & 0xf000) << 12);
    b |= (b << 4);
    

    Notice that, one &(and) operation is saved from your solution. :-)
    Demo.

提交回复
热议问题