frombase16

function frombase16( base16str [, ignore] ) --> str, err

Description

Decodes a base 16 encoded string to a data string. It is possible to ignore characters like \n in base16str via the optional ignore string.

Parameters

base16str

The base 16 encoded string that should be decoded.

ignore

String that represents a optional set of characters that should be ignored in base16str.

Return Values

str

The decoded data string or nil if an error occurs.

err

A message that explains the error, otherwise nil.

Code

--ZFUNC-frombase16-v1
local function frombase16( base16str, ignore ) --> str, err
   local errchar = "unexpected character at position %d: '%s'"

   if ignore then base16str = base16str:gsub( "["..ignore.."]", "" ) end

   local i = string.find( base16str, "[^%x]" )
   if i then
      return nil, string.format( errchar, i, string.sub( base16str, i, i ) )
   end

   return ( base16str:gsub( '..', function ( cc )
               return string.char( tonumber( cc, 16 ) )
            end ) )
end

return frombase16

Examples

local t = require( "tapered" )
local frombase16 = require( "frombase16" )

-- read data from a upper and lower hex string
t.is( frombase16( "48656C6C6F20776F726C6421" ), "Hello world!" )
t.is( frombase16( "48656c6c6f20776f726c6421" ), "Hello world!" )

-- allows to ignore characters in a hex string", function()
t.is( frombase16( "4865-6c6c 6f20-776f 726c-6421", " -" ), "Hello world!" )

-- handles wrong characters without a crash
local res, err = frombase16( "4865-6c6c" )
t.nok( res )
t.is( err, "unexpected character at position 5: '-'" )

t.done()

Inspired by

See also