How do I convert string of hex digits to value it represents in Lua


You use tonumber:

local someHexString = "03FFACB"
local someNumber = tonumber(someHexString, 16)

Note that numbers are not in hexadecimal. Nor are they in decimal, octal, or anything else. They're just numbers. The number 0xFF is the same number as 255. "FF" and "255" are string representations of the same number.


Related videos on Youtube

Author by


Updated on March 22, 2020


  • Sambardo
    Sambardo about 3 years

    I'm reading in a lot of lines of hex data. They come in as strings and I parse them for line_codes which tell me what to do with the rest of the data. One line sets a most significant word of an address (MSW), another line sets the least significant (LSW).

    I then need to concatenate those together such that if MSW = "00ff" and LSW = "f10a" address would be 00fff10a.

    This all went fine, but then I was supposed to check if address was between a certain set of values:

    if address <= "007FFFh" and address >= "000200h" then
        print "I'm in"

    As you all probably know, Lua is not a fan of this as it gives me an error using <= and >= with strings.

    If there a way I can convert the string into hex, such that "FFFF" would become 0xFFFF?

    • Alex
      Alex almost 12 years
      New drinking game: take a shot every time someone brings up that Lua is not an acronym.
  • Sambardo
    Sambardo almost 12 years
    Well, I haven't tested it yet, but I'm sure that will do what I need when I get back to it haha.