Convert 0x1234 to 0x11223344

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

    This works and may be easier to understand, but bit manipulations are so cheap that I wouldn't worry much about efficiency.

    #include 
    #include 
    
    void main() {
      unsigned int c = 0x1234, b;
    
      b = (c & 0xf000) * 0x11000 + (c & 0x0f00) * 0x01100 +
          (c & 0x00f0) * 0x00110 + (c & 0x000f) * 0x00011;
    
      printf("%x -> %x\n", c, b);
    } 
    

提交回复
热议问题