Quick Tip: Converting To & From A Hexidecimal

CSS accepts Red/Green/Blue color values written in either of two ways:
  1. An array (each value can be 0 - 255)
    background: rgb(255,255,255);
  2. A hexidecimal (each digit can be 0 - F)
    background: #FFFFFF;
The hex method uses base 16 to codify all values up to 255 in just two digits.
The letters A - F represent the numbers 10 - 15 respectively.
  • F1 = (15 * 16) + (1 * 1) = 241
  • 09 = (00 * 16) + (9 * 1) = 9

---

For the color picker, we needed an easy way to convert between the two notational values. 
Fortunately, Javascript has built in methods just for this, toString & parseInt.
(Both of which accept a number representing the base or radix that we are computing by.)

Converting to Hex:

var white = 255;
white = white.toString(16);
// white == 'ff'

Great! ...as long as the input value is above 15.  Otherwise, the returned value will be only one digit and will likely confuse the browser.
Since Javascript lacks an internal padding function, we will have to wing it:

var black = 0;
black = black.toString(16);
if (black.length < 2) black = '0' + black;
//black == '00'

There are better all purpose pad functions, but this is good for our needs.
BTW, all browsers can accept a 3 digit hex value, but when only one of the three colors is one digit that won't work.

Done.

Converting from Hex:

var white = FF;
white = parseInt(white, 16);
// white == '255'

Simple, no?!
One last thing - if you use Mootools, this is already built into functions called rgbToHex() and hexToRgb(), which is even simpler!
 var arr = '#FF0000'.hexToRgb();
// arr == [255,0,0]
Loading mentions Retweet

Comments (2)

Feb 26, 2010
lesle said...
Uh, typo alert:
F1 = (16 * 16) + (1 * 16) = 212
Mar 11, 2010
siteroller said...
@ lesle.
Thanks!
I am not sure what your math does, but we did indeed have a typo.
It's been fixed in the article, the number should add up now.

Leave a comment...

 
Got an account with one of these? Login here, or just enter your comment below.
Posterous-login    twitter


 

About