Related Tags

python
communitycreator

# How to convert hex to RGB and RGB to hex in Python Harsh Jain

In this shot, we are going to see how we can convert any hexadecimal color code value to its RGB format equivalent and vice-versa. Let’s see them one by one.

## Converting hex to RGB

We will use the following approach to convert hex color codes into RGB format:

• The RGB format has three values: Red, Green, and Blue.
• Hex color codes have a length of 6, i.e., they can contain 6 hex values (like BAFD32, AAFF22, etc).
• We need to take two hex values for one RGB value, convert those two hex values to decimal values, and then perform the same step with the other values.
• We will get 3 values that correspond to RGB values.

Let’s see how this can be implemented in the code.

def hex_to_rgb(hex):
rgb = []
for i in (0, 2, 4):
decimal = int(hex[i:i+2], 16)
rgb.append(decimal)

return tuple(rgb)

print(hex_to_rgb('FFA501'))
Convert Hex to RGB in Python

Explanation

• In line 1, we define the hex_to_rgb() function that accepts the hex color code values.
• In line 3, we run the loop by taking two hex values from the color code at a time.
• In line 4, we convert the two hex values to their decimal representation by specifying the base as 16 in the int() function.
• Finally, in line 7, we return the result in tuple formatthe format in which RGB values are stored.

Now, let’s see how we can convert the RGB values to their hex representation.

## Converting RGB to hex

To convert RGB values to hex values, we are going to take the three RGB values and convert them to their hex representation using :X while returning the hex value.

Now, let’s take a look at the the code.

def rgb_to_hex(r, g, b):
return ('{:X}{:X}{:X}').format(r, g, b)

print(rgb_to_hex(255, 165, 1))
Convert RGB to Hex in Python

Explanation

• In line 1, we define the rgb_to_hex() function that accepts three RGB values.
• In line 2, we create the hex values using the {:X} formatter that automatically converts decimal values to hex values. Then, we return the result.
• Finally, in line 4, we call the function and pass in the RGB values.

RELATED TAGS

python
communitycreator

CONTRIBUTOR Harsh Jain
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time 