W3docs

How to Convert RGB to Hex and Vice Versa

Read this tutorial and learn several methods that are used for converting the RGB value to Hexadecimal value easily with the help of JavaScript function.

In this tutorial, we suggest several methods of converting RGB to Hex and vice versa. Let’s convert RGB value to Hex value. There are two versions of rbgtoHex which expect integer values for r, g and b.

This following code does RGB to Hex conversion and add any required zero padding:

Javascript convert RGB to Hex

javascript— editable

Here is the alternative way to the above method:

Javascript convert RGB to Hex

javascript— editable

Now let’s convert hex into RGB:

Javascript convert Hex to RGB

javascript— editable

There is another version of <kbd class="highlighted">hexToRgb()</kbd> that also parses a shorthand hex triplet:

Javascript convert hexToRGB method

javascript— editable

HEX and RGB

Hexadecimal (also known as base 16, or hex) is a positional numeral system with a radix of 16. It uses 16 distinct symbols 0–9 for representing values zero to nine, and A–F for representing values ten to fifteen.

The RGB colour is an additive colour model in which red, green and blue are added together to reproduce an array of colours. Each parameter specifies the intensity of the colour and can be an integer between 0 and 255 or a percentage value between 0% and 100%.