34

I want to convert a 3-digit hex color which is coming from HTML CSS to a 6-digit hex color for Flex. Can anyone give me code to convert 3-digit hex colors to their 6-digit equivalents?

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Trinu
  • 1,721
  • 3
  • 21
  • 41

6 Answers6

55

The three digit hex colors are expanded by doubling each digit (see w3 spec). So #F3A gets expanded to #FF33AA.

Yves M.
  • 29,855
  • 23
  • 108
  • 144
mrab
  • 2,702
  • 1
  • 17
  • 10
11

Double every digit: for example #A21 is equal to #AA2211.

However this question is a duplicate of: convert to 3-digit hex color code

Community
  • 1
  • 1
dash1e
  • 7,677
  • 1
  • 30
  • 35
9

Other answers provided the process but I will provide the code using regex and the java programming language

String value = "#FFF";
value = value.replaceAll("#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])", "#$1$1$2$2$3$3");
Ovokerie Ogbeta
  • 503
  • 7
  • 5
1

If you came here and is using Python, here's how:

hex_code = '#FFF'
new_hex_code = '#{}'.format(''.join(2 * c for c in hex_code.lstrip('#')))
bertdida
  • 4,988
  • 2
  • 16
  • 22
1

Kotlin version of Ovokerie's answer:

shortHexString.replace(Regex("#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])"), "#$1$1$2$2$3$3")
Peter Keefe
  • 1,095
  • 14
  • 22
1

PHP Version:

  /**
 * returns a clean 6 digit hex number as a string
 * @param $hex
 * @return false|string
 */
function clean_hex_color($hex)
{
    $hex = strtolower($hex);
    //remove the leading "#"
    if (strlen($hex) == 7 || strlen($hex) == 4)
        $hex = substr($hex, -(strlen($hex) - 1));

    // $hex like "1a7"
    if (preg_match('/^[a-f0-9]{6}$/i', $hex))
        return $hex;
    // $hex like "162a7b"
    elseif (preg_match('/^[a-f0-9]{3}$/i', $hex))
        return $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
    //any other format
    else
        return "000000";
}
Gogo
  • 292
  • 8
  • 19