serialization - 将数字转换为以字节为单位的浮点数
问题描述
我知道 lua 使用双精度数字格式,所以我想知道是否有办法将数字直接转换为字符串作为浮点值(4 个字节),以便我可以通过 udp 套接字发送它
解决方案
对于 Lua 5.3+
local function float32_binary_dump(value)
return ("<f"):pack(value)
end
对于 Lua 5.1+
local function float32_binary_dump(value)
local img, s, h, d = 2^32 - 2^22, "", 1
if value == value then
img = 2^31 - 2^23
if value < 0 or value == 0 and 1/value < 0 then
value, img = -value, 2^32 - 2^23
end
if value > 0.5 * 2^-149 and value < 2^128 then
-- rounding 64-bit double to 32-bit float
d = math.floor(math.log(value)/math.log(2) + 0.5)
d = value < 2^d and d - 1 or d
local e = 2^(d < -126 and -149 or d - 23)
value = value + 0.5 * e
local r = value % e
value = value - (r == 0 and value % (e + e) or r)
end
-- dumping 32-bit image of float
if value < 2^-149 then
img = img - (2^31 - 2^23)
elseif value <= 2^128 - 2^104 then
if d < -126 then
d, h = -126, 0
end
img = img + (value / 2^d + (d - (-126)) * h - 255) * 2^23
end
end
-- convert 32-bit image to little-endian string
while #s < 4 do
local b = img % 256
s = s..string.char(b)
img = (img - b) / 256
end
return s
end
推荐阅读
- angular - 在 JHipster 应用程序中切换语言时如何更改日期区域设置?
- laravel - Laravel 中的过滤功能
- npm - “font-awesome”和“components-font-awesome”之间的区别?
- android - Android 应用程序在没有堆栈的情况下崩溃:如何调试?
- javascript - 如何将本地存储项目从 Cordova 应用程序持久保存到手机?
- node.js - mongoose 文档值可以是函数吗?
- qt-creator - 尝试在 qt creator 上运行项目时出现 [makefile:36:debug] Error1 错误
- windows - 如何在脚本中读取 Windows 7 上的通知栏?
- gcc - gcc 不会编译为可执行文件
- javascript - 将对象数组中的所有数据汇总到新的对象数组中