Convert number to float in bytes

Viewed 266

I know that lua uses double precision number formats so I wonder if there is a way to convert number directly into string as float value (4 bytes) so that I could send it over udp socket

1 Answers

For Lua 5.3+

local function float32_binary_dump(value)
   return ("<f"):pack(value)
end

For 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
Related