KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Hex to RGB Color Codes
PRODUCT: 4D | VERSION: 11 | PLATFORM: Mac & Win
Published On: November 19, 2009
Your current browser may not allow you to download the asset. We recommend Mozilla Firefox or Google Chrome.
Log In

It is easy to use and pass hexadecimal values to represent colors in the RGB format. Some situations (such as using SVG) require the extended decimal format for the Red, Green, and Blue values. The following 4D Method, "Hex2RGB" will take a text based Hex value and parse it into three decimal values: R, G, and B.

When calling this method, pass in the Hex value as text and pointers to three numeric variables which will be filled with the R, G, and B values.

 ` Method: Hex2RGB
 `
 ` Parameters
 ` $1 - Hex Value
 `
 ` Returns
 ` $2 - pointer to a numeric (R)
 ` $3 - pointer to a numeric (G)
 ` $4 - pointer to a numeric (B)


C_TEXT($1;$hex_t)
C_POINTER($2;$3;$4)
C_POINTER($red_p;$green_p;$blue_p)

If (Count parameters>=4)
 $hex_t:=$1

 Case of
  :(Not((Type($2->)=Is Integer)|(Type($2->)=Is LongInt)|(Not((Type($2->)=Is Real)))))
  :(Not((Type($3->)=Is Integer)|(Type($3->)=Is LongInt)|(Not((Type($3->)=Is Real)))))
  :(Not((Type($4->)=Is Integer)|(Type($4->)=Is LongInt)|(Not((Type($4->)=Is Real)))))
  Else
   C_LONGINT($len_l;$value_l;$index_l;$dec_l)
   $red_p:=$2
   $green_p:=$3
   $blue_p:=$4

   $len_l:=Length($hex_t)
   For ($index_l;$len_l;1;-1)
    Case of
     : ($hex_t[[$index_l]]="A")
      $value_l:=10
     : ($hex_t[[$index_l]]="B")
      $value_l:=11
     : ($hex_t[[$index_l]]="C")
      $value_l:=12
     : ($hex_t[[$index_l]]="D")
      $value_l:=13
     : ($hex_t[[$index_l]]="E")
      $value_l:=14
     : ($hex_t[[$index_l]]="F")
      $value_l:=15
     Else
      $value_l:=Num($hex_t[[$index_l]])
    End case

    If ($index_l<$len_l)
     $dec_l:=$dec_l+($value_l*(16^($len_l-$index_l)))
    Else
     $dec_l:=$dec_l+$value_l
    End if
   End for

   $red_p->:=0
   $green_p->:=0
   $blue_p->:=0

   If ($dec_l>0)
    $red_p->:=$dec_l >> 16
    $dec_l:=$dec_l-($red_p-> << 16)
    $green_p->:=($dec_l >> 8)
    $blue_p->:=$dec_l-($green_p-> << 8)
   End if
 End case
End if