annotate 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
rev   line source
jerome@65 1 local M, sbyte, schar, sgsub, sformat = {}, string.byte, string.char, string.gsub, string.format
jerome@65 2 local inf, nan = math.huge, math.huge-math.huge
jerome@65 3
jerome@65 4 local hexbin = {} for i=0,255 do
jerome@65 5 local h, b = sformat("%02x", i), schar(i)
jerome@65 6 hexbin[sformat("%02X", i)], hexbin[h], hexbin[b] = b, b, h
jerome@65 7 end
jerome@65 8
jerome@65 9 function M.uint32_le(s, pos)
jerome@65 10 local d, c, b, a = sbyte(s, (pos or 0)+1, (pos or 0) + 4)
jerome@65 11 return a*256^3 + b*256^2 + c*256 + d
jerome@65 12 end
jerome@65 13 function M.uint16_le(s, pos)
jerome@65 14 local b,a = sbyte(s, (pos or 0)+1, (pos or 0) + 2)
jerome@65 15 return a*256 + b
jerome@65 16 end
jerome@65 17 function M.uint32_be(s, pos)
jerome@65 18 local a,b,c,d = sbyte(s, (pos or 0)+1, (pos or 0) + 4)
jerome@65 19 return a*256^3 + b*256^2 + c*256 + d
jerome@65 20 end
jerome@65 21 function M.uint40_be(s, pos)
jerome@65 22 local a, b, c, d, e = sbyte(s, (pos or 0)+1, (pos or 0) + 5)
jerome@65 23 return a*256^4 + b*256^3 + c*256^2 + d*256 + e
jerome@65 24 end
jerome@65 25 function M.float32_le(s, pos)
jerome@65 26 local a, b, c, d = sbyte(s, (pos or 0) + 1, (pos or 0) + 4)
jerome@65 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
jerome@65 28 if e > 0 and e < 255 then
jerome@65 29 return s * (1+f/2^23) * 2^(e-127)
jerome@65 30 else
jerome@65 31 return e == 0 and (s * f/2^23 * 2^-126) or f == 0 and (s * inf) or nan
jerome@65 32 end
jerome@65 33 end
jerome@65 34 function M.int32_le(s, pos)
jerome@65 35 local d, c, b, a = sbyte(s, (pos or 0)+1, (pos or 0) + 4)
jerome@65 36 return a*256^3 + b*256^2 + c*256 + d - (a < 128 and 0 or 2^32)
jerome@65 37 end
jerome@65 38
jerome@65 39 function M.to_le32(n)
jerome@65 40 local n = n % 2^32
jerome@65 41 return schar(n % 256, (n / 256) % 256, (n / 256^2) % 256, (n / 256^3) % 256)
jerome@65 42 end
jerome@65 43 function M.to_be40(n)
jerome@65 44 local n = n % 2^40
jerome@65 45 return schar((n / 256^4) % 256, (n / 256^3) % 256, (n / 256^2) % 256, (n / 256) % 256, n % 256)
jerome@65 46 end
jerome@65 47
jerome@65 48 function M.to_bin(hs)
jerome@65 49 return hs and sgsub(hs, "%x%x", hexbin)
jerome@65 50 end
jerome@65 51 function M.to_hex(bs)
jerome@65 52 return bs and sgsub(bs, ".", hexbin)
jerome@65 53 end
jerome@65 54
jerome@65 55 return M