Wednesday, May 16, 2012

Functions to convert Hex 2 RGB and vice-versa

These are for autohotkey and in AHK code. Taken from Autohotkey forums topic 1878:

  • From Hexadecimal to RGB
  • From RGB to Hexadecimal
  • Check for a valid hexadecimal value

From Hexadecimal to RGB:
HEX2RGB(HEXString,Delimiter="")
{
 If Delimiter=
    Delimiter=,
 
 StringMid,R,HexString,1,2
 StringMid,G,HexString,3,2
 StringMid,B,HexString,5,2

 R = % "0x"R 
 G = % "0x"G
 B = % "0x"B
 
 R+=0
 G+=0
 B+=0

 RGBString = % R Delimiter G Delimiter B

Return RGBString
}


From RGB to Hexadecimal:
RGB2HEX(RGBString,Delimiter="") 
{ 
 If Delimiter=
    Delimiter=,
 StringSplit,_RGB,RGBString,%Delimiter%

 SetFormat, Integer, Hex 
 _RGB1+=0
 _RGB2+=0
 _RGB3+=0

 If StrLen(_RGB1) = 3
    _RGB1= 0%_RGB1%

 If StrLen(_RGB2) = 3
    _RGB2= 0%_RGB2%

 If StrLen(_RGB3) = 3
    _RGB3= 0%_RGB3%

 SetFormat, Integer, D 
 HEXString = % _RGB1 _RGB2 _RGB3
 StringReplace, HEXString, HEXString,0x,,All
 StringUpper, HEXString, HEXString

Return, HEXString
}


Just in case, check a valid hexadecimal value:
CheckHexC(HEXString)
{
  StringUpper, HEXString, HEXString

  RGB:=HEX2RGB(HEXString)
  CHK:=RGB2HEX(RGB)

  StringUpper, CHK, CHK

  If CHK=%HEXString%
     Return 1
  else
     Return 0
}

Add comment

Please note: all comments are reviewed before being published.


Security code
Refresh

Member Login

Joes Latest Members

A huge WELCOME goes to today's newest members:

  • infonat
Member Signups (Activated)
BeforeCurrentTrend
Day21=
Week105ê
Month11224ê
Year2,265612ê

Member Stats
68 guests are currently online.
1,178 members are still deciding.
There are 5,935 members in total.

Latest Comments

Paypal Donations

Want to support my work? Any donation is a blessing :c)