-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathutilities_vendor.lua
More file actions
76 lines (62 loc) · 2.08 KB
/
utilities_vendor.lua
File metadata and controls
76 lines (62 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
-- https://stackoverflow.com/questions/18886447/convert-signed-ieee-754-float-to-hexadecimal-representation
-- lua-MessagePack
function float2hex (n)
if n == 0.0 then return 0.0 end
local sign = 0
if n < 0.0 then
sign = 0x80
n = -n
end
local mant, expo = math.frexp(n)
local hext = {}
if mant ~= mant then
hext[#hext+1] = string.char(0xFF, 0x88, 0x00, 0x00)
elseif mant == math.huge or expo > 0x80 then
if sign == 0 then
hext[#hext+1] = string.char(0x7F, 0x80, 0x00, 0x00)
else
hext[#hext+1] = string.char(0xFF, 0x80, 0x00, 0x00)
end
elseif (mant == 0.0 and expo == 0) or expo < -0x7E then
hext[#hext+1] = string.char(sign, 0x00, 0x00, 0x00)
else
expo = expo + 0x7E
mant = (mant * 2.0 - 1.0) * math.ldexp(0.5, 24)
hext[#hext+1] = string.char(sign + math.floor(expo / 0x2),
(expo % 0x2) * 0x80 + math.floor(mant / 0x10000),
math.floor(mant / 0x100) % 0x100,
mant % 0x100)
end
return tonumber(string.gsub(table.concat(hext),"(.)",
function (c) return string.format("%02X%s",string.byte(c),"") end), 16)
end
local function bytevals2float(b1, b2, b3, b4)
local sign = b1 > 0x7F
local expo = (b1 % 0x80) * 0x2 + math.floor(b2 / 0x80)
local mant = ((b2 % 0x80) * 0x100 + b3) * 0x100 + b4
if sign then
sign = -1
else
sign = 1
end
local n
if mant == 0 and expo == 0 then
n = sign * 0.0
elseif expo == 0xFF then
if mant == 0 then
n = sign * math.huge
else
n = 0.0/0.0
end
else
n = sign * math.ldexp(1.0 + mant / 0x800000, expo - 0x7F)
end
return n
end
function bytes2float (c)
local b1,b2,b3,b4 = string.byte(c:reverse(), 1, 4)
return bytevals2float(b1, b2, b3, b4);
end
-- UNIT TEST.
assert( 1.0 == bytevals2float( 0x3F, 0x80, 0x00, 0x00 ) );
assert( 5.5 == bytevals2float( 0x40, 0xb0, 0x00, 0x00 ) );