RGB vs. Hex colors
Tags: color, rgb, hex, javascript
Published: 2023-12-07 19:24:59

Whilst working on a recent javascript browser application involving color selection I was curious about what the difference between RGB and Hex colors were. Below is an aggregation of the differences I found plus some code to convert between the two. 

**Transparency**
The first and only material difference between RGB and Hex is that you can easily add a transparency value to RGB. RGBA() in javascript/CSS allows you to specify a transparency value thats between 0 and 1 with 1 being full opaque. ex. RGBA(255, 255, 255, .5)

**RGB Readability**
RGB is easier for humans to interpreter as each value corresponds to the intensity of the red, green, or blue values being emitted by the LCDs of the screen. The min value being 0 and max value being 255. 0 being no light is emitted and 255 meaning the the pixel is at full intensity for that color (assuming you are using an LED screen). 255 being the max value as the human eye cannot detect more than 255 levels per color. Conveniently colors are often stored as 8 bits which 2^8=256 options per color.

**Hex Convenience**
The only explanation I was able to find for the existence of hex color values was that they are easier and shorter to write. Hex is just the 0-255 value from rgb converted to base 16 or hexadecimal. With hexadecimal 10, 11, 12, 13, 14 and 15 correspond to A, B, C, D, E, and F in that order. This allows a 3 digit color to be represented as only 2 digits in hex making a hex value only 7 digits long once you account for the # prefix. 

**Hex to RGB Conversion**

```
const HEXtoRGB = hex => {
//checks for short hand hex values and converts to unshortened version
    hex = hex.replace(/#/g, '');
    if (hex.length === 3) {
        hex = hex.split('').map(function (hex) {
            return hex + hex;
        }).join('');
    }
//regex returns variable results which is an array of [total hex value, first hex value, second hex value, third hex value]
    var result = /^([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})[\da-z]{0,0}$/i.exec(hex);
//ParseInt(x, 16) returns x as a base 16 number
    if (result) {
        var red = parseInt(result[1], 16);
        var green = parseInt(result[2], 16);
        var blue = parseInt(result[3], 16);

        return [red, green, blue];
    } else {
        // invalid color
        return null;
    }
};
```

**RGB to Hex Conversion**

```
const RGBtoHEX = rgb => {
//checks to make sure rgb is valid and converts to an array with colors split out
    rgb = rgb.match(/^rgba?\(\s?(\d+),?\s?(\d+),?\s?(\d+),?\s?\/?\s?(\d?\.?\d+|\d+)%?\)$/i);
//initializes hex variable
    let hex = '';
//if rgb is a valid rgb format the below will make sure the rgb value is between 0 and 255
    if (rgb) {
        var red = rgb[1] < 0 ? 0 : rgb[1] > 255 ? 255 : rgb[1];
        var green = rgb[2] < 0 ? 0 : rgb[2] > 255 ? 255 : rgb[2];
        var blue = rgb[3] < 0 ? 0 : rgb[3] > 255 ? 255 : rgb[3];
//concatenates # + each color value in hex
        hex = "#" +
//toString takes a paramater of base which is inherited when toString is used on a number
//The "0" and .slice(-2) are in case the hex value is 1 digit the 0 is required to keep the format correct
            ("0" + parseInt(red, 10).toString(16)).slice(-2) +
            ("0" + parseInt(green, 10).toString(16)).slice(-2) +
            ("0" + parseInt(blue, 10).toString(16)).slice(-2)
    }
    return hex;
};

```

**sources:**
Youtube video explaining LED displays: https://www.youtube.com/watch?v=uyLDA9QT8EY&ab_channel=BasicsExplained%2CH3Vtux

Historical source of RGB and hex particularly the response from Philip Yip:
https://www.quora.com/What-is-the-history-behind-why-we-use-hex-color-codes

Hexadecimal colors:
https://en.wikipedia.org/wiki/Hexadecimal

Converting hex to RGB:
https://www.pluralsight.com/blog/tutorials/understanding-hexadecimal-colors-simple#:~:text=a%20hex%20code%3F-,Hex%20color%20codes%20are%20one%20type%20of%20HTML%20color%20code,of%20values%20in%20binary%20code.

Website with full list of color conversions:
https://www.html-code-generator.com/javascript/color-converter-script