squirrel

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


Solution

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