frombase2
function frombase2( base2str [, ignore] ) --> str, err
Description
Decodes a base 2 encoded string(bitfield) to a data string. It is possible to ignore characters like \n in base2str via the optional ignore string.
-
0, O and o are valid values for 0
-
1, I, i, L and l are valid values for 1
Parameters
- base2str
-
The bitfield that should be decoded.
- ignore
-
String that represents a optional set of characters that should be ignored in base2str.
Return Values
- str
-
The decoded data string or nil if an error occurs.
- err
-
A message that explains the error, otherwise nil.
Code
--ZFUNC-frombase2-v1 local function frombase2( base2str, ignore ) --> str, err local bitMap = { o="0", i="1", l="1" } local errchar = "unexpected character at position %d: '%s'" if ignore then base2str = base2str:gsub( "["..ignore.."]", "" ) end base2str = string.lower( base2str ) base2str = base2str:gsub( "[ilo]", function( c ) return bitMap[ c ] end ) local i = string.find( base2str, "[^01]" ) if i then return nil, string.format( errchar, i, string.sub( base2str, i, i ) ) end return base2str:gsub( '........', function ( cc ) return string.char( tonumber( cc, 2 ) ) end ) end return frombase2
Examples
local t = require( "taptest" ) local frombase2 = require( "frombase2" ) -- reads data from a bitfields string t( frombase2( "01000001010000110100010001000011" ), "ACDC" ) -- read data with o instead of 0 t( frombase2( "o1ooooo1o1oooo11" ), "AC" ) t( frombase2( "OioooooiOiooooii" ), "AC" ) -- allows to ignore characters in a bitfield string t( frombase2( "o1ooooo1 o1oooo11", " " ), "AC" ) -- handles wrong characters without a crash local res, err = frombase2( "o1oo*ooo1*o1oo*oo11" ) t( res, nil ) t( err, "unexpected character at position 5: '*'" ) t()