Skip to content

Instantly share code, notes, and snippets.

@teamon
Created September 4, 2010 14:54
Show Gist options
  • Select an option

  • Save teamon/565245 to your computer and use it in GitHub Desktop.

Select an option

Save teamon/565245 to your computer and use it in GitHub Desktop.
#define HEXCHAR2INT(x, y) ((x >= 'a' ? x-87 : x-48) * 16 + (y >= 'a' ? y-87 : y-48))
float * _parse_color(const char * str){
int size = strlen(str);
float * ret = new float[4];
switch(size){
case 4: // #rgb
ret[0] = HEXCHAR2INT(str[1], str[1]) / 255.0;
ret[1] = HEXCHAR2INT(str[2], str[2]) / 255.0;
ret[2] = HEXCHAR2INT(str[3], str[3]) / 255.0;
ret[3] = 1.0;
break;
case 5: // #rgba
ret[0] = HEXCHAR2INT(str[1], str[1]) / 255.0;
ret[1] = HEXCHAR2INT(str[2], str[2]) / 255.0;
ret[2] = HEXCHAR2INT(str[3], str[3]) / 255.0;
ret[3] = HEXCHAR2INT(str[4], str[4]) / 255.0;
break;
case 7: // #rrggbb
ret[0] = HEXCHAR2INT(str[1], str[2]) / 255.0;
ret[1] = HEXCHAR2INT(str[3], str[4]) / 255.0;
ret[2] = HEXCHAR2INT(str[5], str[6]) / 255.0;
ret[3] = 1.0;
break;
case 9: // #rrggbbaa
ret[0] = HEXCHAR2INT(str[1], str[2]) / 255.0;
ret[1] = HEXCHAR2INT(str[3], str[4]) / 255.0;
ret[2] = HEXCHAR2INT(str[5], str[6]) / 255.0;
ret[3] = HEXCHAR2INT(str[7], str[8]) / 255.0;
break;
}
return ret;
}
import scala.util.matching.Regex
def color(name: String) = {
val RGB = """#([a-f0-9])([a-f0-9])([a-f0-9])""".r
val RGBA = """#([a-f0-9])([a-f0-9])([a-f0-9])([a-f0-9])""".r
val RRGGBB = """#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})""".r
val RRGGBBAA = """#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})""".r
def s(s: String) = {
val x = Integer.parseInt(s, 16)
(x*16 + x) / 255.0
}
def p(s: String) = Integer.parseInt(s, 16) / 255.0
name match {
case RGB(r,g,b) => List(r,g,b).map(s)
case RGBA(r,g,b,a) => List(r,g,b,a).map(s)
case RRGGBB(r,g,b) => List(r,g,b).map(p)
case RRGGBBAA(r,g,b,a) => List(r,g,b,a).map(p)
case _ => println("Cannot parse color: " + name)
}
}
val xs = List("#100", "#f905", "#ff000011", "#ff99cc")
println(xs)
println(xs.map(color(_)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment