Parse integer in base 10 to base 16 in Squirrel

350 Views Asked by At

How should I do base 10 to base 16 integer conversion in Squirrel? In Javascript I can do this with: parseInt("ff", 16).

I'm trying to do a HEX color code to RGB calculator for an Electric Imp. #ffaaccwould be split into 3 parts (ff, aa and cc). I would then calculate these to base 10 integers and achieve RGB(255, 170, 204). These numbers I will then use to control an RGB led with PWM.

2

There are 2 best solutions below

0
On BEST ANSWER

Here's one approach using array.find (and format for reversal):

local lookup = ['0','1','2','3','4','5','6','7','8','9',
                'a','b','c','d','e','f']
local hex = "7f"
local dec = lookup.find(hex[0]) * 0x10 + lookup.find(hex[1])
server.log(format("%s -> %d -> %02x", hex, dec, dec))
0
On

Try String tointeger() function.

local s = "ff";
print (s.tointeger(16));

If you want convert conversely, try format() function.

local i = 255;
print (format("%x", i));