comparison support/casc/bin.lua @ 65:8b8b0bade520

Fixed support for mounts using the new MountJournal and mount IDs (no conversion of old profiles at the moment).
author Jerome Vuarand <jerome.vuarand@gmail.com>
date Thu, 23 Oct 2014 13:44:59 +0100
parents
children
comparison
equal deleted inserted replaced
64:49ae7191821f 65:8b8b0bade520
1 local M, sbyte, schar, sgsub, sformat = {}, string.byte, string.char, string.gsub, string.format
2 local inf, nan = math.huge, math.huge-math.huge
3
4 local hexbin = {} for i=0,255 do
5 local h, b = sformat("%02x", i), schar(i)
6 hexbin[sformat("%02X", i)], hexbin[h], hexbin[b] = b, b, h
7 end
8
9 function M.uint32_le(s, pos)
10 local d, c, b, a = sbyte(s, (pos or 0)+1, (pos or 0) + 4)
11 return a*256^3 + b*256^2 + c*256 + d
12 end
13 function M.uint16_le(s, pos)
14 local b,a = sbyte(s, (pos or 0)+1, (pos or 0) + 2)
15 return a*256 + b
16 end
17 function M.uint32_be(s, pos)
18 local a,b,c,d = sbyte(s, (pos or 0)+1, (pos or 0) + 4)
19 return a*256^3 + b*256^2 + c*256 + d
20 end
21 function M.uint40_be(s, pos)
22 local a, b, c, d, e = sbyte(s, (pos or 0)+1, (pos or 0) + 5)
23 return a*256^4 + b*256^3 + c*256^2 + d*256 + e
24 end
25 function M.float32_le(s, pos)
26 local a, b, c, d = sbyte(s, (pos or 0) + 1, (pos or 0) + 4)
27 local s, e, f = d > 127 and -1 or 1, (d % 128)*2 + (c > 127 and 1 or 0), a + b*256 + (c % 128)*256^2
28 if e > 0 and e < 255 then
29 return s * (1+f/2^23) * 2^(e-127)
30 else
31 return e == 0 and (s * f/2^23 * 2^-126) or f == 0 and (s * inf) or nan
32 end
33 end
34 function M.int32_le(s, pos)
35 local d, c, b, a = sbyte(s, (pos or 0)+1, (pos or 0) + 4)
36 return a*256^3 + b*256^2 + c*256 + d - (a < 128 and 0 or 2^32)
37 end
38
39 function M.to_le32(n)
40 local n = n % 2^32
41 return schar(n % 256, (n / 256) % 256, (n / 256^2) % 256, (n / 256^3) % 256)
42 end
43 function M.to_be40(n)
44 local n = n % 2^40
45 return schar((n / 256^4) % 256, (n / 256^3) % 256, (n / 256^2) % 256, (n / 256) % 256, n % 256)
46 end
47
48 function M.to_bin(hs)
49 return hs and sgsub(hs, "%x%x", hexbin)
50 end
51 function M.to_hex(bs)
52 return bs and sgsub(bs, ".", hexbin)
53 end
54
55 return M