Convert 0x1234 to 0x11223344

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

    If multiplication is cheap and 64-bit arithmetics is available, you could use this code:

    uint64_t x = 0x1234;
    x *= 0x0001000100010001ull;
    x &= 0xF0000F0000F0000Full;
    x *= 0x0000001001001001ull;
    x &= 0xF0F0F0F000000000ull;
    x = (x >> 36) * 0x11;
    std::cout << std::hex << x << '\n';
    

    In fact, it uses the same idea as the original attempt by AShelly.

提交回复
热议问题