Convert hex to decimal keeping fractional part in Lua

Posted by Zack Mulgrew on Stack Overflow See other posts from Stack Overflow or by Zack Mulgrew
Published on 2010-04-21T20:03:01Z Indexed on 2010/04/21 20:13 UTC
Read the original article Hit count: 186

Filed under:
|
|

Lua's tonumber function is nice but can only convert unsigned integers unless they are base 10. I have a situation where I have numbers like 01.4C that I would like to convert to decimal.

I have a crummy solution:

function split(str, pat)
   local t = {} 
   local fpat = "(.-)" .. pat
   local last_end = 1
   local s, e, cap = str:find(fpat, 1)
   while s do
      if s ~= 1 or cap ~= "" then
        table.insert(t,cap)
      end
      last_end = e+1
      s, e, cap = str:find(fpat, last_end)
   end
   if last_end <= #str then
      cap = str:sub(last_end)
      table.insert(t, cap)
   end
   return t
end
-- taken from http://lua-users.org/wiki/SplitJoin

function hex2dec(hexnum)
  local parts = split(hexnum, "[\.]")
  local sigpart = parts[1]
  local decpart = parts[2]

  sigpart = tonumber(sigpart, 16)
  decpart = tonumber(decpart, 16) / 256

  return sigpart + decpart
end

print(hex2dec("01.4C")) -- output: 1.296875

I'd be interested in a better solution for this if there is one.

© Stack Overflow or respective owner

Related posts about lua

Related posts about hex