首页 > 解决方案 > 将数字转换为以字节为单位的浮点数

问题描述

我知道 lua 使用双精度数字格式,所以我想知道是否有办法将数字直接转换为字符串作为浮点值(4 个字节),以便我可以通过 udp 套接字发送它

标签: serializationluafloating-point

解决方案


对于 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

推荐阅读