rectangletangle - 1 year ago 92
Python Question

# How do I convert a hex triplet to an RGB tuple and back?

I'd like to convert a hex triplet to an RGB tuple and then convert a tuple to a hex triplet.

You can use a look-up table with some slicing and shifts — all relatively fast operations — to create a couple of functions that will work unchanged in both Python 2 and 3:

``````_NUMERALS = '0123456789abcdefABCDEF'
_HEXDEC = {v: int(v, 16) for v in (x+y for x in _NUMERALS for y in _NUMERALS)}
LOWERCASE, UPPERCASE = 'x', 'X'

def rgb(triplet):
return _HEXDEC[triplet[0:2]], _HEXDEC[triplet[2:4]], _HEXDEC[triplet[4:6]]

def triplet(rgb, lettercase=LOWERCASE):
return format(rgb[0]<<16 | rgb[1]<<8 | rgb[2], '06'+lettercase)

if __name__ == '__main__':
print('{}, {}'.format(rgb('aabbcc'), rgb('AABBCC')))
# -> (170, 187, 204), (170, 187, 204)

print('{}, {}'.format(triplet((170, 187, 204)),
triplet((170, 187, 204), UPPERCASE)))
# -> aabbcc, AABBCC

print('{}, {}'.format(rgb('aa0200'), rgb('AA0200')))
# -> (170, 2, 0), (170, 2, 0)

print('{}, {}'.format(triplet((170, 2, 0)),
triplet((170, 2, 0), UPPERCASE)))
# -> aa0200, AA0200
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download