RGB to Hex

Anyone who designs graphics for the Web is plenty familiar with RGB colors. And they've probably seen their editing programs convert RGB to hex automatically. How that happens exactly may not be as familiar of a topic to most. It's a little confusing to think of how a set of three different RGB values can somehow become a single, hexidecimal code. And just how accurate is the conversion? Does anything get lost in the translation?

Interestingly enough, the conversion from RGB to hex is more precise than you might think. The formula uses a combination of numbers (1-9) and letters (A-F). The process starts by taking the first RGB value and dividing that number by 16. Let's take a look at a set of RGB values:

R=77
B=131
G=50

Take the first RGB value and divide that by 16. Drop the remainder for this step. This will be the first character in your hex code.

R - 77 / 16 = 4.812 = 4 (first hex code character)

Now multiply the original remainder by 16 and round up. This will be the next hex code character.

.812 x 16 = 12.99 = 13 (second character in code)

Hmmm...13 is too big a character to be in a hex color code. Let's use a letter code instead. Replace numbers 10 - 15 with letters A through F (A=10, B=11, C=12, etc). In our example, that means the second character (13) will be letter D. Now the first character in my hex code is 4D. Repeat the process for each RGB number, and you've converted RGB to Hex.