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
2008-10-18 01:38:12
He wrote an equation. RGB to hex is reading right to left. Hex to RGB is reading left to right.
Jonathan Tran
2008-10-18 01:43:13
+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
2008-10-18 01:39:21
Careful of your operator precedence: + has higher precedence than <<
Adam Rosenfield
2008-10-18 02:29:58
Paul Wicks
2010-05-21 06:53:00
+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
2008-10-18 01:57:11
+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
2008-10-18 06:02:40