简体   繁体   中英

Parse integer in base 10 to base 16 in Squirrel

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. #ffaacc would 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.

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));

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM