Convert 0x1234 to 0x11223344

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

    Another way is:

    DWORD OrVal(DWORD & nible_pos, DWORD input_val, DWORD temp_val, int shift)
    {
        if (nible_pos==0)
            nible_pos = 0x0000000F;
        else
            nible_pos = nible_pos << 4;
        DWORD nible = input_val & nible_pos;
        temp_val |= (nible << shift);
        temp_val |= (nible << (shift + 4));
        return temp_val;
    }
    
    DWORD Converter2(DWORD input_val)
    {
        DWORD nible_pos = 0x00000000;
        DWORD temp_val = 0x00000000;
        temp_val = OrVal(nible_pos, input_val, temp_val, 0);
        temp_val = OrVal(nible_pos, input_val, temp_val, 4);
        temp_val = OrVal(nible_pos, input_val, temp_val, 8);
        temp_val = OrVal(nible_pos, input_val, temp_val, 12);
        return temp_val;
    }
    
    DWORD val2 = Converter2(0x1234);
    

    An optimized version (3 times faster):

    DWORD Converter3(DWORD input_val)
    {
        DWORD nible_pos = 0;
        DWORD temp_val = 0;
        int shift = 0;
        DWORD bit_nible[4] = { 0x000F, 0x000F0, 0x0F00, 0xF000 };
    
        for ( ; shift < 16; shift+=4 )
        {
            if (nible_pos==0)
                nible_pos = 0x0000000F;
            else
                nible_pos = nible_pos << 4;
            DWORD nible = input_val & nible_pos;
            temp_val |= (nible << shift);
            temp_val |= (nible << (shift + 4));
        }
    
        return temp_val;
    }
    
    
    0 讨论(0)
提交回复
热议问题