Return to Snippet

Revision: 41597
at February 20, 2011 23:07 by Sverri


Initial Code
/*--------------------------------------------------------------------
 *
 * Turn a HEX colour value into its 3 character equivalent.
 *
 * The colour of the shorthand will differ slightly from the original
 * in some cases. This is because we loose half the storage capacity,
 * from 6 to 3 nibbles (24 to 12 bits).
 *
 */
function hex_to_shorthand($hex, $uppercase=true)
{
  // Remove preceding hash if present
  if ($hex[0] == "#") $hex = substr($hex, 1);
  
  // If it already is shorthand, nothing more to do here
  if (strlen($hex) == 3) return "#$hex";
  
  // If it is not 6 characters long then it is invalid
  elseif (strlen($hex) !== 6) return "";
  
  // The final shorthand HEX value
  $final = "";
  
  // Get the triplets
  $triplets = str_split($hex, 2);
  
  // Go over each triplet separately
  foreach ($triplets as $t)
  {
    // Get the decimal equivalent of triplet
    $dec = base_convert($t, 16, 10);
    
    // Find the remainder
    $remainder = $dec % 17;
    
    // Go to the nearest decimal that will yield a double nibble
    $new = ($dec%17 > 7) ? 17+($dec-$remainder) : $dec-$remainder;
    
    // Convert decimal into HEX
    $hex = base_convert($new, 10, 16);
    
    // Add one of the two identical nibbles
    $final .= $hex[0];
  }
  // Return the shorthand HEX colour value
  return $uppercase ? strtoupper($final) : strtolower($final);
}

/*--------------------------------------------------------------------
 *
 * 25 samples...
 *
 */
echo "<style>p{margin:0;padding:.75em;font-size:1.4em;}</style>";
for ($i=0; $i<25; $i++) {
  $original = substr(str_shuffle("0000011111222223333344444555556666677777"
  . "8888899999FFFFFEEEEEDDDDDCCCCCBBBBBAAAAA"), 0, 6);
  $newcolor = hex_to_shorthand($original);
  echo "<p style='background:#$original;'>Longhand: <b>#$original</b></p>";
  echo "<p style='background:#$newcolor;'>Shorthand: <b>#$newcolor</b></p>";
  echo "<br>";
}

Initial URL


Initial Description
Turn a HEX colour value into its 3 character equivalent.

Initial Title
Longhand HEX colour to shorthand equivalent

Initial Tags


Initial Language
PHP