It’s actually easier than it sounds, and once you understand the basics you can likely do most conversions mentally.
The goal is to take a color in the RGB format, 3 groups of integers 3 digits long (eg: 111, 222, 123) and convert it to the hexadecimal equivalent.
Hexadecimal is essentially a different way to count. Instead of increasing numerally past the number 9 it increments in letters from 10-15. So instead of 9 10 11 12 13 14 15 we would have 9 A B C D E F.
The hexadecimal format works by taking a string of integers, let’s use 255 as an example, and starts subtracting the largest amount it can from the first two integers, then takes the remainder, adds it to the final integer if one exists, and checks for it’s hexadecimal equivalent.
So in the case of 255, we start out with the first two digits, 25, and take out our first hex equivalent, F or 15. That leaves 10 left from 25, so we take 10 and add it to the final integer, 5 to get 15 or F. That would make our hex equivalent of ‘FF.’
And, well, that’s really all there is to it!
Before we jump into the JavaScript, one thing to note is that in order to convert to an actual number, none of the 3 groups of integers may be greater than 255. This is due to the limits that an 8-bit byte can hold.
So how do we convert to hex using JavaScript?
var string = 255; string.toString(16);
You can even shorten the process to one line by writing:
(255).toString(16);
Hexadecimal can be confusing, but don’t let that discourage you from trying to understand it. Try it out in your console a few times and it will start to make more sense.