Convert 0x1234 to 0x11223344

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

    unsigned long transform(unsigned long n)
    {
    
        /* n: 00AR
         *    00GB
         */
        n = ((n & 0xff00) << 8) | (n & 0x00ff);
    
        /* n: 0AR0
         *    0GB0
         */
        n <<= 4;
    
        /* n: AAR0
         *    GGB0
         */
        n |= (n & 0x0f000f00L) << 4;
    
        /* n: AARR
         *    GGBB
         */
        n |= (n & 0x00f000f0L) >> 4;
    
        return n;
    }
    

    The alpha and red components are shifted into the higher 2 bytes where they belong, and the result is then shifted left by 4 bits, resulting in every component being exactly where it needs to be.

    With a form of 0AR0 0GB0, a bit mask and left-shift combination is OR'ed with the current value. This copies the A and G components to the position just left of them. The same thing is done for the R and B components, except in the opposite direction.

提交回复
热议问题