2 -- Copyright (C) 2013 Toni Gundogdu <legatvs@gmail.com>
4 -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
6 -- This program is free software: you can redistribute it and/or
7 -- modify it under the terms of the GNU Affero General Public
8 -- License as published by the Free Software Foundation, either
9 -- version 3 of the License, or (at your option) any later version.
11 -- This program is distributed in the hope that it will be useful,
12 -- but WITHOUT ANY WARRANTY; without even the implied warranty of
13 -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 -- GNU Affero General Public License for more details.
16 -- You should have received a copy of the GNU Affero General
17 -- Public License along with this program. If not, see
18 -- <http://www.gnu.org/licenses/>.
23 -- Returns an array of the numerical codes of the hexadecimal string.
25 if not (#s
% 2 ==0) then
26 error(string.format('%s: invalid hexstring', s
))
28 local B
= require
'bit'
30 s
:gsub('%x%x', function(n
)
31 table.insert(r
, B
.tobit(tonumber(n
,16)))
36 -- Returns an array of the internal numerical codes of the characters.
37 function M
.to_bytes(s
)
39 s
:gsub('.', function(c
)
40 table.insert(r
, c
:byte(1))
45 -- Returns a hexadecimal string created from the array of the internal
46 -- numberical codes of the characters.
47 function M
.from_bytes(b
)
48 local B
= require
'bit'
50 for _
,v
in pairs(b
) do
51 table.insert(r
, B
.tohex(v
,2))
53 return table.concat(r
,'')
56 -- Data to a hexadecimal string.
60 return M
.from_bytes(M
.to_bytes(s
))
61 elseif t
== 'table' then
62 return M
.from_bytes(s
)
64 error(string.format('invalid type: %s', t
))
68 -- Returns a string of the internal numerical codes created from
69 -- the hexadecimal string or the array of numerical codes of the
70 -- hexadecimal string.
73 if type(s
) == 'string' then
75 elseif type(s
) == 'table' then
78 error(string.format('invalid type: %s', t
))
81 for _
,v
in pairs(a
) do
82 table.insert(r
, string.char(v
))
84 return table.concat(r
,'')
92 function test_eq(t,r,e)
93 if not (r == e) then error(string.format('%s: failed', t)) end
97 test_eq('test/to_hex #1', M.to_hex({0x0b,0x02,0x04,0x08,0xa}), '0b0204080a')
98 test_eq('test/to_hex #2', M.to_hex('foo'), '666f6f')
101 test_eq('test/to_str #1', M.to_str({0x66,0x6f,0x6f}), 'foo')
102 test_eq('test/to_str #2', M.to_str('666f6f'), 'foo')
107 -- vim: set ts=2 sw=2 tw=72 expandtab: