在纯Lua中解析IEEE754双精度浮点数?
我有以 IEEE754 格式编码的固定大小的双精度数组,任何人都可以向我指出任何可以执行相关操作的 Lua 代码吗?
更新:我无法发布这个问题,因为它太短了,所以这里是我在解决这个问题的过程中编写的一些代码 - 这会将二进制字符串转换为像 "0011000"< 这样的位字符串/代码>
-- get string of bits for given byte
function byte2bits(i)
local result=""
for c=1,8 do
nextByte = i % 2
i = (i - nextByte)/2
result = result .. nextByte
end
return string.reverse(result)
end
-- get a string of bits from string of bytes
function str2bits(s)
result=''
for i = 1, string.len(s) do
--print(string.byte(s, i))
result=result .. byte2bits(string.byte(s,i))
end
return result
end
I have fixed size array of doubles encoded in IEEE754 format, can anyone point me to any Lua code that can do something related?
Update: I can't post this question because it's too short, so here's some code I wrote in process of figuring this out — this converts binary string into string of bits like "0011000"
-- get string of bits for given byte
function byte2bits(i)
local result=""
for c=1,8 do
nextByte = i % 2
i = (i - nextByte)/2
result = result .. nextByte
end
return string.reverse(result)
end
-- get a string of bits from string of bytes
function str2bits(s)
result=''
for i = 1, string.len(s) do
--print(string.byte(s, i))
result=result .. byte2bits(string.byte(s,i))
end
return result
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我实际上需要这样做并来这里寻求答案。看起来以前没有人这样做过,所以我最终自己做了一些东西。我没有详尽地测试每种情况,但它能够可靠地正确编码和解码数字,并且输入和输出数字之间没有错误。
我编写的函数使用二进制字符串,但任何需要它的人都应该能够轻松地调整它以适应自己的用途。
这是我的代码:
I actually needed to do this and came here for an answer. Doesn't look like anyone has done this before, so I ended up making something myself. I've not tested every case exhaustively, but it's able to reliably encode and decode numbers correctly, with no error between the input and output numbers.
The functions I wrote work with binary strings, but anyone who needs this should be able to easily adapt it for their own uses.
Here's my code:
8 年后,幸运的是,情况发生了变化:
这里有一个仍在更新的纯 lua 库,它与其他结构库非常相似:https://luarocks.org/modules/deepakjois/vstruct
在其他格式中,它可以解析任何字节顺序的浮点数和双精度数。
例子:
After 8 years the landscape has fortunately changed:
A still being updated pure lua library that closely resembles other struct libraries exists here: https://luarocks.org/modules/deepakjois/vstruct
Among other formats it can parse both floats and doubles in any endianess.
Example: