将十六进制转换为十进制,保留Lua中的小数部分
Lua的tonumber函数很好,但只能转换无符号整数,除非它们是以10为基数的。我有一种情况,我想把像将十六进制转换为十进制,保留Lua中的小数部分,lua,decimal,hex,Lua,Decimal,Hex,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 ca
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
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")) -- output: 1.296875
功能拆分(str、pat)
局部t={}
本地fpat=“(.-)”。。拍打
本地最后\u端=1
局部s,e,cap=str:find(fpat,1)
当我们做的时候
如果s~=1或cap~='',则
表.插入(t,cap)
结束
最后一端=e+1
s、 e,cap=str:find(fpat,last_end)
结束
如果last_end将“heximal”点向右移动两位,转换为十进制,然后除以256
014C ==> 332 / 256 = 1.296875
如果您的Lua是使用C99编译器(或者可能是早期的gcc)编译的,那么
下面是一个更简单的解决方案:
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
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")) -- output: 1.296875
这是否记录在Lua文档中?这是如此简单,我觉得错过它愚蠢…它没有文档记录,并且依赖于实现/配置。在您的luaconf.h中有一个#define lua#u str2number(s,p)strtod((s),(p))——因此这完全取决于strtod的C库实现,或者您在luaconf.hGood中使用的任何东西。不管怎样,这就是我要用的。谢谢+1这是一个很好的解决方案,但对于我的特殊情况,我发现道格的答案是最直接的。对于我目前使用的平台以外的平台,我将使用此解决方案。谢谢