Over Christmas I started working on a ColdFusion image library and wrote a nice hex to RGB function. I used a few tricks to make it as fast as possible. I'll write more about some of the optimizations in the coming week. Let me know if you can identify a way to make it even faster.

view plain print about
1<cffunction name="HexToRGB" access="public" output="false" returntype="struct" hint="hex to struct r,g,b,a">
2    <cfargument name="hex" type="string" required="true" hint="3 or 6 digit hex value (valid examples: ##FFF, FFF, ##FFFFFF, FFFFFF)">
3
4 <cfset var retVal = structNew()>
5 <cfset var i = 0>
6 <cfset var o = 0>
7 <cfset var offset = 0>
8
9    <!--- cheaper in time to look for a leading '#' and set an offset than burn a call to removeChars --->
10    <cfif mid(arguments.hex, 1, 1) EQ chr(35)>
11     <cfset offset = 1>
12 </cfif>
13
14    <!--- Remove non-hex values. the following is faster than regex --->
15     <cfloop from="#1 + offset#" to="#len(arguments.hex)#" index="i">
16     <cfif find(mid(arguments.hex, i + o, 1), '0123456789ABCDEFabcdef') EQ 0>
17     <cfset arguments.hex = removeChars(arguments.hex, i + o, 1)>
18     <cfset o = o - 1>
19     </cfif>
20 </cfloop>
21
22 <cfif len(arguments.hex) EQ (3 + offset)>
23 <cfset retVal.r = InputBaseN(mid(arguments.hex, 1 + offset, 1) & mid(arguments.hex, 1 + offset, 1), 16)>
24 <cfset retVal.g = InputBaseN(mid(arguments.hex, 2 + offset, 1) & mid(arguments.hex, 2 + offset, 1), 16)>
25 <cfset retVal.b = InputBaseN(mid(arguments.hex, 3 + offset, 1) & mid(arguments.hex, 3 + offset, 1), 16)>
26 <cfelse>
27 <cfset retVal.r = InputBaseN(mid(arguments.hex, 1 + offset, 2), 16)>
28 <cfset retVal.g = InputBaseN(mid(arguments.hex, 3 + offset, 2), 16)>
29 <cfset retVal.b = InputBaseN(mid(arguments.hex, 5 + offset, 2), 16)>
30 </cfif>
31
32 <cfset retVal.a = 255>
33    
34 <cfreturn retVal>
35</cffunction>