Debian Codegraph @

extensions/Scribunto/includes/Engines/LuaCommon/lualib/luabit/hex.lua

raw symbols SCIP
1 --[[---------------
2 Hex v0.4
3 -------------------
4 Hex conversion lib for lua.
5
6 How to use:
7 hex.to_hex(n) -- convert a number to a hex string
8 hex.to_dec(hex) -- convert a hex string(prefix with '0x' or '0X') to number
9
10 Part of LuaBit(http://luaforge.net/projects/bit/).
11
12 Under the MIT license.
13
14 copyright(c) 2006~2007 hanzhao ([email protected])
15
16 2013-02-20: Brad Jorsch: Fix to not try messing with globals, doesn't work in Scribunto
17 --]]---------------
18
19 local bit = require 'bit'
20
21 do
22
23 local function to_hex(n)
24 if(type(n) ~= "number") then
25 error("non-number type passed in.")
26 end
27
28 -- checking not float
29 if(n - math.floor(n) > 0) then
30 error("trying to apply bitwise operation on non-integer!")
31 end
32
33 if(n < 0) then
34 -- negative
35 n = bit.tobits(bit.bnot(math.abs(n)) + 1)
36 n = bit.tonumb(n)
37 end
38
39 local hex_tbl = {'A', 'B', 'C', 'D', 'E', 'F'}
40 local hex_str = ""
41
42 while(n ~= 0) do
43 local last = math.mod(n, 16)
44 if(last < 10) then
45 hex_str = tostring(last) .. hex_str
46 else
47 hex_str = hex_tbl[last-10+1] .. hex_str
48 end
49 n = math.floor(n/16)
50 end
51 if(hex_str == "") then
52 hex_str = "0"
53 end
54 return "0x" .. hex_str
55 end
56
57 local function to_dec(hex)
58 if(type(hex) ~= "string") then
59 error("non-string type passed in.")
60 end
61
62 local head = string.sub(hex, 1, 2)
63
64 if( head ~= "0x" and head ~= "0X") then
65 error("wrong hex format, should lead by 0x or 0X.")
66 end
67
68 return tonumber(string.sub(hex, 3), 16)
69 end
70
71 --------------------
72 -- hex lib interface
73 local hex = {
74 to_dec = to_dec,
75 to_hex = to_hex,
76 }
77
78 return hex
79
80 end
81
82 --[[
83 -- test
84 d = 4341688
85 h = to_hex(d)
86 print(h)
87 print(to_dec(h))
88
89 for i = 1, 100000 do
90 h = hex.to_hex(i)
91 d = hex.to_dec(h)
92 if(d ~= i) then
93 error("failed " .. i .. ", " .. h)
94 end
95 end
96 --]]