【发布时间】:2011-02-10 18:51:10
【问题描述】:
Lua 的 tonumber 函数很好,但只能转换无符号整数,除非它们以 10 为底。我有一种情况,我想将 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
如果有更好的解决方案,我会对此感兴趣。
【问题讨论】: