13

I've been using 3-digit hex color values in CSS for a long time: #fff, #999, #069, etc. I can see how the repeating letters/numbers are merged to create a 3-digit hex color code, but I don't fully understand the pattern to be able to write a converter in PHP. Is there documentation for this?

Edit: Oh, perhaps my question wasn't clear. I need to know how some of the 6-digit hex color values are converted to 3-digits. xxxxxx (ffffff) and xxyyzz (006699) – these are the only two patterns, correct?

Rory O'Kane
  • 29,210
  • 11
  • 96
  • 131
eozzy
  • 66,048
  • 104
  • 272
  • 428
  • Which way are you looking at converting? From 3 to 6-digit? Or from hex to decimal? – peirix Sep 22 '09 at 10:30
  • The benefits of a converter would surely be very limited. After all, only a small proportion of color codes can be simplified, and for a saving of only 3 characters per code. I'd be surprised if there's any documentation, but as a programming exercise, it's probably useful. – pavium Sep 22 '09 at 10:32
  • Oh, perhaps my question wasn't clear. I need to know how some of the 6 digit hex color values are converted to 3-digits? xxxxxx (ffffff) xxyyzz (006699), these are the only two patterns, correct? – eozzy Sep 22 '09 at 17:55

4 Answers4

36

To convert a 3-character hex code into a 6 character one, you need to repeat each character:

$hex = '#fff';
$hex6 = '#' . $hex[1] . $hex[1] . $hex[2] . $hex[2] . $hex[3] . $hex[3];

If you want to convert it to decimal you can use the hexdec function

Greg
  • 316,276
  • 54
  • 369
  • 333
4

3 digit CSS code is short for 6 digits": #06a; is #0066aa;
Each two digits represent a number from 0 to 255.
Converting these values to hex and back is all you need.

Kobi
  • 135,331
  • 41
  • 252
  • 292
3

#f0f is expanded to #ff00ff so basically you just need to calculate the value and the value times 16 for each character, e.g.:

#f98: f = 15 => red = 15 + 15*16 = 255 etc.

jensgram
  • 31,109
  • 6
  • 81
  • 98
  • Ah, I seem to have missed the point - and my sense of consulting the API (`hexdec()`). – jensgram Sep 22 '09 at 10:32
  • So, using this logic, you can just reverse it by dividing by 16 in order to get the hex 3 version? – Josh Jul 23 '15 at 17:05
  • @Josh Well, yes. But you'll effectively restrict yourself to a granularity of 16 per channel instead of 256. – jensgram Jul 27 '15 at 04:56
2

function hexfix(str) {
  var v, w;
  v = parseInt(str, 16); // in rrggbb
  if (str.length == 3) {
    // nybble colors - fix to hex colors
 //  0x00000rgb              -> 0x000r0g0b
 //  0x000r0g0b | 0x00r0g0b0 -> 0x00rrggbb
 w = ((v & 0xF00) << 8) | ((v & 0x0F0) << 4) | (v & 0x00F);
 v = w | (w << 4);
  }
  return v.toString(16).toUpperCase();
 }

var hex1 = 'AABBCC',
    hex2 = 'ABC';

document.body.appendChild(document.createTextNode(hex1+" becomes "+hexfix(hex1)+'.  '));
document.body.appendChild(document.createTextNode(hex2+" becomes "+hexfix(hex2)+'.  '));

Something like this.