Lua的tonumber函数很好,但只能转换无符号整数,除非它们是10的基数.我有一种情况,我有像01.4C这样的数字,我想转换为十进制. 我有一个糟糕的解决方案: function split(str, pat) local t = {} local
我有一个糟糕的解决方案:
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
如果有的话,我会对这个更好的解决方案感兴趣.
如果你的Lua是用C99编译器(或者更早的gcc)编译的,那么……~ e$lua Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio > return tonumber"0x01.4C" 1.296875
