In CSS we could use either RGB values or hex code to set value of a color. But have you ever thought about why we could do this? At least for me I have never thought about such question until doing a related challenge on freeCodeCamp.
For example when it comes to magenta, we can either use #FF00FF
in hex code or rgb(255, 0, 255)
in RGB values. Use RGB values for color is easy to understand. But what the hell is hex code? How could it represent for the same color as RGB values do. It turns out that hex code is just another format of RGB values.
Let’s see a picture.
Through the picture we can easily find that hex code could be divided into three parts and each part is just hexadecimal format of its related color value. Specifically the two character on the left is hexadecimal format of red value, the two character on the middle is hexadecimal format of green value and the two character on the right is hexadecimal format of blue value.
Now we know the structure of hex code. It's time to write some Python codes to convert between them.
Convert Hex to RGB
At first we need to define a function to convert hex to decimal.
hexToDecimalDict = {
"0": 0,
"1": 1,
"2": 2,
"3": 3,
"4": 4,
"5": 5,
"6": 6,
"7": 7,
"8": 8,
"9": 9,
"A": 10,
"B": 11,
"C": 12,
"D": 13,
"E": 14,
"F": 15,
"a": 10,
"b": 11,
"c": 12,
"d": 13,
"e": 14,
"f": 15
}
def hexToDecimal(hexCode):
length = len(hexCode)
return reduce(
lambda x, y: x + y,
[hexToDecimalDict[hexCode[i]]*16**(length - i - 1) for i in range(0, length)]
)
print hexToDecimal("FF") # output 255
With the help of function hexToDecimal()
, it's so easy to convert hex color to its GRB mode.
def hexToRGB(hexColor):
n = 2
return "rgb(%s)" % ", ".join([str(hexToDecimal(hexColor[i:i+n])) for i in range(1, len(hexColor), n)])
print hexToRGB("#10458F") # output 'rgb(16, 69, 143)'
Alternatively we can use a build-in function int()
to convert hex to decinal. Try to replace hexToDecimal(hexColor[i:i+n])
with int(hexColor[i:i+n], 16)
you will get the same answer.
Convert RGB to Hex
Just as above we need to define a function to convert decimal to hex.
decimalToHexArr = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"]
def decimalToHex(decimalValue, hexCode=""):
if decimalValue < 16:
return "0x" + decimalToHexArr[decimalValue] + hexCode
quotient = decimalValue / 16
remainder = decimalValue % 16
return decimalToHex(quotient, decimalToHexArr[remainder] + hexCode)
decimalToHex(143) # output '0x8F'
It's also very easy to convert RGB color to its hex format.
import re
def RGBToHex(RGBColor):
return "#%s" % "".join([
decimalToHex(int(x.strip()))[2:] for x in re.search("\((.*)\)", RGBColor).group(1).split(",")
])
RGBToHex("rgb(16, 69, 143)") # output '#10458F'
There is also a build-in function hex()
which can realize the same function as decimalToHex()
do.
After learn how to convert RGB color to its hex format and vice versa, I'm also curious about two more questions about CSS color.
Why there is a symbol ‘#’ in the hex code?
It turns out that the symbol is just a representation of hexadecimal. Nothing more.
Why RGB value is between 0 to 255?
There are totally 256 possibilities from 0 to 255. 256 is exactly 2 to the 8th power which is 8 bits. 8 bits is exactly 1 byte. What a coincidence! It turns out that the range of RGB value is exactly designed for 1 byte. If you are wondering why 1 byte is equal to 8 bits, the answer from Quora is really helpful.