hex.lua (pre 5.0.5)

Added by iNTERFACEWARE

Encodes strings of ASCII characters as their hex equivalents, superseded by the builtin filter.hex methods

Source Code
hex = {}

local HexToDec={
 ['0'] = 0,  ['1'] = 1,  ['2'] = 2,  ['3'] = 3,
 ['4'] = 4,  ['5'] = 5,  ['6'] = 6,  ['7'] = 7,
 ['8'] = 8,  ['9'] = 9,  ['A'] = 10, ['B'] = 11,
 ['C'] = 12, ['D'] = 13, ['E'] = 14, ['F'] = 15,
 ['A'] = 10, ['B'] = 11, ['C'] = 12, ['D'] = 13,
 ['E'] = 14, ['F'] = 15
}

local DecToHex='0123456789ABCDEF'

local function char(S, i)  
   local B1 = HexToDec[S:sub(i,i)]
   local B2 = HexToDec[S:sub(i+1,i+1)]
   local C = B1 *16 + B2
   return C
end

-- Public interface
function hex.dec(S)
   print(#S)
   local D = S:gsub("%s", '')
   D = D:gsub("\n", '')
   print(#D)

   local T = {}
   local i = 1
   local c = 1
   while (i < #D ) do
      local C = char(D,i)
      i = i + 2
      T[c] = string.char(C)
      c = c + 1
   end
   return table.concat(T)
end

function hex.enc(S)
   local T = {}
   local j = 1
   local B
   for i=1, #S do
      B = S:byte(i) / 16 + 1
      T[j] = DecToHex:sub(B,B)
      B = S:byte(i) % 16 + 1
      T[j+1] = DecToHex:sub(B,B)
      j = j + 2
   end
   return table.concat(T)
end
Description
Encodes strings of ASCII characters as their hex equivalents, superseded by the builtin filter.hex methods