Search code examples
colorshexrgb

Converting hex color to RGB and vice-versa


What is the most efficient way to do this?


Solution

  • Real answer: Depends on what kind of hexadecimal color value you are looking for (e.g. 565, 555, 888, 8888, etc), the amount of alpha bits, the actual color distribution (rgb vs bgr...) and a ton of other variables.

    Here's a generic algorithm for most RGB values using C++ templates (straight from ScummVM).

    template<class T>
    uint32 RGBToColor(uint8 r, uint8 g, uint8 b) {
    return T::kAlphaMask |
           (((r << T::kRedShift) >> (8 - T::kRedBits)) & T::kRedMask) |
           (((g << T::kGreenShift) >> (8 - T::kGreenBits)) & T::kGreenMask) |
           (((b << T::kBlueShift) >> (8 - T::kBlueBits)) & T::kBlueMask);
    }
    

    Here's a sample color struct for 565 (the standard format for 16 bit colors):

    template<>
    struct ColorMasks<565> {
    enum {
        highBits    = 0xF7DEF7DE,
        lowBits     = 0x08210821,
        qhighBits   = 0xE79CE79C,
        qlowBits    = 0x18631863,
    
    
        kBytesPerPixel = 2,
    
        kAlphaBits  = 0,
        kRedBits    = 5,
        kGreenBits  = 6,
        kBlueBits   = 5,
    
        kAlphaShift = kRedBits+kGreenBits+kBlueBits,
        kRedShift   = kGreenBits+kBlueBits,
        kGreenShift = kBlueBits,
        kBlueShift  = 0,
    
        kAlphaMask = ((1 << kAlphaBits) - 1) << kAlphaShift,
        kRedMask   = ((1 << kRedBits) - 1) << kRedShift,
        kGreenMask = ((1 << kGreenBits) - 1) << kGreenShift,
        kBlueMask  = ((1 << kBlueBits) - 1) << kBlueShift,
    
        kRedBlueMask = kRedMask | kBlueMask
    
    };
    };