[ACCEPTED]-convert to 3-digit hex color code-hex

Accepted answer
Score: 36

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

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

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

Score: 4

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

Score: 3

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

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

Score: 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.

0

More Related questions