views:

3574

answers:

4

What is the most efficient way to do this?

+2  A: 

A hex value is just RGB numbers represented in hexadecimal. So you just have to take each pair of hex digits and convert them to decimal.

Example:

#FF6400 = RGB(0xFF, 0x64, 0x00) = RGB(255, 100, 0)

yjerem
He wrote an equation. RGB to hex is reading right to left. Hex to RGB is reading left to right.
Jonathan Tran
+3  A: 

just real quick:

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

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

int b = hexcolor & 0xFF;

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

Bill James
Careful of your operator precedence: + has higher precedence than <<
Adam Rosenfield
Paul Wicks
Nice.. answer's been there for 1.5 years and no one caught that.
Bill James
+1  A: 

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

};
};
Vicent Marti
+8  A: 

In python:

def hex_to_rgb(value):
    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(rgb):
    return '#%02x%02x%02x' % rgb

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'
Jeremy Cantrell
nice python snippet, thanks!
Daniel T. Magnusson