将十六进制转换为十进制,保留 Lua 中的小数部分
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
如果有的话,我会对更好的解决方案感兴趣。
Lua's tonumber function is nice but can only convert unsigned integers unless they are base 10. I have a situation where I have numbers like 01.4C
that I would like to convert to decimal.
I have a crummy solution:
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
I'd be interested in a better solution for this if there is one.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一个更简单的解决方案:
Here is a simpler solution:
如果你的 Lua 是用 C99 编译器(或者更早的 gcc)编译的,那么......
If your Lua is compiled with a C99 compiler (or maybe earlier gcc), then...
将“十六进制”点向右移动两位,转换为十进制,然后除以 256。
Move the "heximal" point two places to the right, convert to decimal, and then divide by 256.