# How to convert RGB to Hex Color Code in Python

The RGB-to-hexadecimal converter algorithm is straightforward: ensure that your R, G, and B (red, green, and blue) values are in the range 0…255, convert R, G, and B to hex strings, and then concatenate the three hex strings. Here’s how to convert RGB to Hex color values in Python.

## Colors in the RGB format

The RGB color scheme is made up of three colors: red, green, and blue.

(R, G, and B)

The red, green, and blue colors each have 8 bits, with integer values varying from 0 to 255.

As a result, the maximum number of colors that can be generated is as follows

``256*256*256 =1000000 to base 16 = 16777216``

A hex color code is a six-digit hexadecimal (base-16) number that looks like this:

``RRGGBB16``
• The two left digits represent the red color.
• The two middle digits represent the color green.
• The two right digits represent the blue color.

Convert the decimal values of red, green, and blue to hexadecimal values.

Concatenate the red, green, and blue hex values to form RRGGBB.

##### Example No. 1

To convert the gold color (255, 215, 0) to a hex color code, use the following formula:

``FF16 = R = 25510 D716 = G = 21510 0016 = B = 010``

So, here’s the hex color code: FFD700 in hexadecimal

##### Example No. 2

To convert the red color (255, 0, 0) to a hex color code, use the following formula:

``FF16 = R = 25510 0016 = G = 010 0016 = B = 010``

So, here’s the hex color code: FF0000 is the hexadecimal equivalent.

## Programmatically convert RGB color to hex color

The code below provides three colors (R, G, and B) and prints -1 if the conversion isn’t possible.

Consider the following examples:

R = 0; G = 0; B = 0; as input

#000000 as Output

R = 255, G = 255, and B = 256 are the input values.

-1 as an output

Explanation: Since a color’s range is limited to 0-255, a 256 color code is not feasible.

#### Methodology

Check to see if each of the specified colors is in the 0-255 range.

If not, print -1 and exit the program since there is no way to convert in this situation.

If they’re within range, convert the given color code to its hexadecimal equivalent for each color.

If the hexadecimal value is a single digit, add 0 to the left to make it a two-digit value.

```# Implementation program to convert RGB color code to Hex color code # Function to convert decimal to hexadecimal