Skip to content

Instantly share code, notes, and snippets.

@Kubuxu
Last active July 31, 2021 13:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kubuxu/e5e04c028d8aaeab4be8 to your computer and use it in GitHub Desktop.
Save Kubuxu/e5e04c028d8aaeab4be8 to your computer and use it in GitHub Desktop.
Two functions allowing for Lua's number serialization.
--[[
The MIT License (MIT)
Copyright (c) 2015 Jakub (Kubuxu) Sztandera
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]--
function readDouble(bytes)
local sign = 1
local mantissa = bytes[2] % 2^4
for i = 3, 8 do
mantissa = mantissa * 256 + bytes[i]
end
if bytes[1] > 127 then sign = -1 end
local exponent = (bytes[1] % 128) * 2^4 + math.floor(bytes[2] / 2^4)
if exponent == 0 then
return 0
end
mantissa = (math.ldexp(mantissa, -52) + 1) * sign
return math.ldexp(mantissa, exponent - 1023)
end
function writeDouble(num)
local bytes = {0,0,0,0, 0,0,0,0}
if num == 0 then
return bytes
end
local anum = math.abs(num)
local mantissa, exponent = math.frexp(anum)
exponent = exponent - 1
mantissa = mantissa * 2 - 1
local sign = num ~= anum and 128 or 0
exponent = exponent + 1023
bytes[1] = sign + math.floor(exponent / 2^4)
mantissa = mantissa * 2^4
local currentmantissa = math.floor(mantissa)
mantissa = mantissa - currentmantissa
bytes[2] = (exponent % 2^4) * 2^4 + currentmantissa
for i= 3, 8 do
mantissa = mantissa * 2^8
currentmantissa = math.floor(mantissa)
mantissa = mantissa - currentmantissa
bytes[i] = currentmantissa
end
return bytes
end
@KrystilizeNevaDies
Copy link

Thanks! This saved me a big headache

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment