title: CSS Hex to Shorthand Hex conversion
body: <p>What is the proper algorithm to convert Hex to Shorthand Hex? For example: <code>#996633</code> easily is converted to <code>#963</code>. But what if it's something like <code>#F362C3</code>?</p>
  <p>My first guess would be that I just take the first value of each color and go with that. So <code>#F362C3</code> becomes <code>#F6C</code>. But I don't know how to mathematically justify that approach.</p>
  <pre><code>function hex_to_shorthand($hex, $uppercase=true)
  {
    // Remove preceding hash if present
    if ($hex[0] == &quot;#&quot;) $hex = substr($hex, 1);
    
    // If it already is shorthand, nothing more to do here
    if (strlen($hex) == 3) return &quot;#$hex&quot;;
    
    // If it is not 6 characters long then it is invalid
    elseif (strlen($hex) !== 6) return &quot;&quot;;
    
    // The final shorthand HEX value
    $final = &quot;&quot;;
    
    // 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 &gt; 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);
  }
  </code></pre>
  <p>This seems a little more involved and again, I'm not sure what the mathematical justification is behind it. So something like <code>#F362C3</code> becomes <code>#E6C</code>, which is not what I would expect.</p>
  <p>What the proper way to do this and what is the mathematical proof behind how the conversion works?</p>
  <p>(The above code is PHP but that can apply to any language)</p>