1if not modules then modules = { } end modules ['l-number'] = {
2 version = 1.001,
3 comment = "companion to luat-lib.mkiv",
4 author = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
5 copyright = "PRAGMA ADE / ConTeXt Development Team",
6 license = "see context related readme files"
7}
8
9
10
11
12local tonumber = tonumber
13local format = string.format
14local concat = table.concat
15local floor = math.floor
16
17number = number or { }
18local number = number
19
20
21
22
23
24
25
26
27local t = {
28 "0", "0", "0", "0", "0", "0", "0", "0",
29 "0", "0", "0", "0", "0", "0", "0", "0",
30 "0", "0", "0", "0", "0", "0", "0", "0",
31 "0", "0", "0", "0", "0", "0", "0", "0",
32}
33
34function number.tobitstring(b,m,w)
35 if not w then
36 w = 32
37 end
38 local n = w
39 for i=0,w-1 do
40 local v = (b>>i) & 0x1
41 local k = w - i
42 if v == 1 then
43 n = k
44 t[k] = "1"
45 else
46 t[k] = "0"
47 end
48 end
49 if w then
50 return concat(t,"",1,w)
51 elseif m then
52 m = 33 - m * 8
53 if m < 1 then
54 m = 1
55 end
56 return concat(t,"",1,m)
57 elseif n < 8 then
58 return concat(t)
59 elseif n < 16 then
60 return concat(t,"",9)
61 elseif n < 24 then
62 return concat(t,"",17)
63 else
64 return concat(t,"",25)
65 end
66end
67
68function number.valid(str,default)
69 return tonumber(str) or default or nil
70end
71
72function number.toevenhex(n)
73 local s = format("%X",n)
74 if #s % 2 == 0 then
75 return s
76 else
77 return "0" .. s
78 end
79end
80
81function number.bytetodecimal(b)
82 local d = floor(b * 100 / 255 + 0.5)
83 if d > 100 then
84 return 100
85 elseif d < -100 then
86 return -100
87 else
88 return d
89 end
90end
91
92function number.decimaltobyte(d)
93 local b = floor(d * 255 / 100 + 0.5)
94 if b > 255 then
95 return 255
96 elseif b < -255 then
97 return -255
98 else
99 return b
100 end
101end
102
103function number.idiv(i,d)
104 return i // d
105end
106 |