Converting hex color to RGB and vice-versa

What is the most efficient way to do this?


Solution 1:

In python:

def hex_to_rgb(value):
    """Return (red, green, blue) for the color given as #rrggbb."""
    value = value.lstrip('#')
    lv = len(value)
    return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))

def rgb_to_hex(red, green, blue):
    """Return color as #rrggbb for the given color values."""
    return '#%02x%02x%02x' % (red, green, blue)

hex_to_rgb("#ffffff")           #==> (255, 255, 255)
hex_to_rgb("#ffffffffffff")     #==> (65535, 65535, 65535)
rgb_to_hex(255, 255, 255)       #==> '#ffffff'
rgb_to_hex(65535, 65535, 65535) #==> '#ffffffffffff'

Solution 2:

In python conversion between hex and 'rgb' is also included in the plotting package matplotlib. Namely

import matplotlib.colors as colors

Then

colors.hex2color('#ffffff')        #==> (1.0, 1.0, 1.0)
colors.rgb2hex((1.0, 1.0, 1.0))    #==> '#ffffff'

The caveat is that rgb values in colors are assumed to be between 0.0 and 1.0. If you want to go between 0 and 255 you need to do a small conversion. Specifically,

def hex_to_rgb(hex_string):
    rgb = colors.hex2color(hex_string)
    return tuple([int(255*x) for x in rgb])

def rgb_to_hex(rgb_tuple):
    return colors.rgb2hex([1.0*x/255 for x in rgb_tuple])

The other note is that colors.hex2color only accepts valid hex color strings.

Solution 3:

just real quick:

int r = ( hexcolor >> 16 ) & 0xFF;

int g = ( hexcolor >> 8 ) & 0xFF;

int b = hexcolor & 0xFF;

int hexcolor = (r << 16) + (g << 8) + b;

Solution 4:

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

};
};