I’m trying to split an RGB string in hex, for example: ‘00cc00’, into three integers. Splitting the string into two character chunks is easy. Is there something similar to STRING.tointeger() that will accept hex? Or has anyone written a function to do this that they’re willing to share?
There is likely a more elegant way to do this but here is a function I wrote you can adapt - it expects a string in the form “0xaBcD11” so you can either rewrite the function or call it with strNumToInt(“0x” + STRING)
`function strNumToInt(str){
local retVal;
if(str == null) return;
try{
if(typeof str == "string" && str.len() >= 3 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X')){
retVal = 0;
local bitShift = 0
local tempVal;
for(local i=str.len()-1; i >= 2 ; i--){
switch(str[i]){
case 'a':
case 'A':
tempVal = 10;
break;
case 'b':
case 'B':
tempVal = 11;
break;
case 'c':
case 'C':
tempVal = 12;
break;
case 'd':
case 'D':
tempVal = 13;
break;
case 'e':
case 'E':
tempVal = 14;
break;
case 'f':
case 'F':
tempVal = 15;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
tempVal = str[i].tointeger() - 48;
break;
default:
server.log("ERROR - INVALID HEX STRING")
return;
}
retVal += tempVal << 4*bitShift++
}
return retVal;
} else {
return str.tointeger();
}
} catch(ex){
retVal = null;
server.log(ex);
}
}`
Thanks, I changed it up a little to not need the ‘0x’.
If anyone knows a more efficient way let me know.
http://forums.electricimp.com/discussion/comment/364#Comment_364
I posted code on how to convert the hex color into values for the RGB LED on the Hannah.
Here are two functions that I put into the imp program:
function Hex2RGB(v)
{
local vString = v.tostring().toupper();
local hexChars = “0123456789ABCDEF”;
// Make sure it's 6 digits long
if(vString.len() == 6)
{
// Return the new colors
return [ (hexChars.find(vString[0].tochar())*16) + hexChars.find(vString[1].tochar()),
(hexChars.find(vString[2].tochar())*16) + hexChars.find(vString[3].tochar()),
(hexChars.find(vString[4].tochar())*16) + hexChars.find(vString[5].tochar()) ];
}
// Just return the existing LED colors
return [led_r, led_g, led_b];
}
function RGB2Hex(r,g,b)
{
return format(r,"%02X") + format(g,"%02X") + format(b,"%02X");
}
Ooh, thats a really neat way of doing it. Thanks!