Lua中如何将十六进制数含小数部分转换成十进制?
- 内容介绍
- 文章标签
- 相关推荐
本文共计310个文字,预计阅读时间需要2分钟。
Lua的`tonumber`函数很强大,但只能转换无符号整数,除非它是10的基数。我有一种情况,我有像01.4C这样的数字,我想将其转换为十六进制。我有一个简单的解决方案:
luafunction split(str, pat) local t={} for str:match((.-) .. pat) do table.insert(t, 1, str) end return tend
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 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
本文共计310个文字,预计阅读时间需要2分钟。
Lua的`tonumber`函数很强大,但只能转换无符号整数,除非它是10的基数。我有一种情况,我有像01.4C这样的数字,我想将其转换为十六进制。我有一个简单的解决方案:
luafunction split(str, pat) local t={} for str:match((.-) .. pat) do table.insert(t, 1, str) end return tend
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 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

