Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert to 3-digit hex color code

Tags:

css

php

hex

colors

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?

like image 454
eozzy Avatar asked Sep 22 '09 10:09

eozzy


People also ask

Can hex be 3 digits?

3 Digit HEX ValueThe 3-digit hex code is a shorthand for some 6-digit hex codes. Where r, g, and b represent the red, green, and blue components with values between 0 and f. The 3-digit hex code can only be used when both the values (RR, GG, and BB) are the same for each component.

What is the three digit color code?

A 3-digit color code is a shorthand version of the normal 6-digit HEX color code. Only 4096 HEX colors out of over 16 millions can be written in shorthand. The two HEX digits of each color in RGB must be the same character so that a HEX color can be shorten to 3 digits.

Are hex codes always 6 digits?

Hex Codes Represent Red, Green and Blue In fact, equal levels of red, green and blue, whatever that level may be, will always produce a shade of gray. The six digits of a hex code are in fact three two-digit numbers, each representing the level of red, green and blue.

What color is #fff in HTML?

#FFF is WHITE.


2 Answers

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.

like image 120
Dan Mecklenburg Avatar answered Oct 06 '22 00:10

Dan Mecklenburg


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

like image 38
Greg Avatar answered Oct 05 '22 22:10

Greg