Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How can I convert a hex colour to RGB()

Usefull Functions & Procedures

How can I convert a hex colour to RGB()

by  ChrisRChamberlain  Posted    (Edited  )
If you want to convert a colour expressed in hex to RGB() format try the following.

Depending on your needs and use, you may need to add additional error trapping to validate the string passed to the function Hex2RGB(), as the function assumes, apart from typos, that the hex string passed is a 'legal' Windows colour.

Thread184-658948 discusses a RGB2Hex() function, and FAQ184-4203 is a Bin - Dec - Hex - RGB Converter
[color blue]
lcRGB = Hex2RGB([#ff00ff])
? lcRGB
[color green]
****************[color blue]
FUNCTION Hex2RGB
LPARAMETERS Str2Convert
LOCAL i, lnPos

DO CASE
CASE SUBSTR(Str2Convert,1,1) # [#]
MESSAGEBOX([Invalid string])
Str2Return = [Error!]
CASE LEN(Str2Convert) # 7
MESSAGEBOX([Invalid string])
Str2Return = [Error!]
OTHE
Str2Return = [RGB(]
lnPos = 2
FOR i = 1 TO 3
lcValue = Hex2Dec(SUBSTR(Str2Convert,lnPos,2))

IF i # 3
Str2Return = Str2Return + lcValue + [,]
ELSE
Str2Return = Str2Return + lcValue + [)]
ENDI
lnPos = lnPos + 2
ENDF
ENDCASE

RETURN Str2Return
[color green]
****************[color blue]
FUNCTION Hex2Dec
LPARAMETERS HexString
LOCAL i, llcChar, lnLen, lnSum, lnPos

lnLen = LEN(HexString)
lnSum = 0
lnPos = 0
FOR i = 1 TO lnLen
lcChar = SUBSTR(HexString,lnLen-lnPos,1)
DO CASE
CASE UPPER(lcChar) = [A]
lcChar = [10]
CASE UPPER(lcChar) = "B"
lcChar = [11]
CASE UPPER(lcChar) = [C]
lcChar = [12]
CASE UPPER(lcChar) = [D]
lcChar = [13]
CASE UPPER(lcChar) = [E]
lcChar = [14]
CASE UPPER(lcChar) = [F]
lcChar = [15]
ENDCASE
lnSum = lnSum + VAL(UPPER(lcChar)) * 16^(i-1)
lnPos = lnPos + 1
ENDFOR

RETURN TRANSFORM(lnSum)[color black]

Have fun! [smile]
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top