将十六进制转换为 Lua 中的十进制,并保留小数部分。

Lua 的 tonumber 函数非常好用,但只能将无符号整数转换为十进制数,除非它们采用的是十进制数制。我有一个需要将类似于 01.4C 的数字转换为十进制的情况。

我有一个不太好的解决方案:

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

如果有更好的解决方案,我会很感兴趣。

原文链接 https://stackoverflow.com/questions/2686169

点赞
stackoverflow用户102937
stackoverflow用户102937

将“heximal”点向右移动两个位置,转换为十进制,然后除以256。

014C  ==>  332 / 256 = 1.296875
2010-04-21 20:06:44
stackoverflow用户33252
stackoverflow用户33252

如果你的 Lua 是用 C99 编译器编译的(或者可能是早期的 gcc),那么...

~ e$ lua
Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> return tonumber"0x01.4C"
1.296875
2010-04-21 20:19:40
stackoverflow用户107090
stackoverflow用户107090

下面是一个更简单的解决方案:

function hex2dec(hexnum)
        local a,b=string.match(hexnum,"(.*)%.(.*)$")
        local n=#b
        a=tonumber(a,16)
        b=tonumber(b,16)
        return a+b/(16^n)
end

print(hex2dec("01.4C")) -- 输出:1.296875
2010-04-21 20:21:28