tocrockford32

function tocrockford32( str ) --> crock32str

Description

Encpdes a data string to a base 32 string using the crockford alphabet.

Parameters

str

The data string that should be encoded.

Return Values

crock32str

The encoded base 32 string.

Code

--ZFUNC-tocrockford32-v1
local function tocrockford32( str ) --> crock32str
   --ZFUNC-asciichunks-v1
   local function asciichunks( str, length )
      length = length or 1
      local chunks = {}

      local i = 1
      local last = string.len( str )
      while i <= last do
         local j = i + length - 1
         table.insert( chunks, str:sub( i, j ) )
         i = i + length
      end

      return chunks
   end

   local bitMap = {
     "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111",
     "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"
   }
   local alphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"

   local bitTab = {}
   for i = 1, #str do
      local b = string.byte( str, i, i )
      local firstHalf = math.floor( b / 2 ^ 4 )
      local secondHalf = b - ( firstHalf * 2 ^ 4 )
      table.insert( bitTab, bitMap[ firstHalf + 1 ] )
      table.insert( bitTab, bitMap[ secondHalf + 1 ] )
   end
   local fullBitStr = table.concat( bitTab )
   local mod5 = #fullBitStr % 5
   if mod5 > 0 then
      fullBitStr = fullBitStr..string.rep( '0', 5 - mod5 )
   end

   local chunks = asciichunks( fullBitStr, 5 )
   local result = {}
   for _, value in ipairs( chunks ) do
      local pos = tonumber( value, 2 ) + 1
      table.insert( result, alphabet:sub( pos, pos ) )
   end

   return table.concat( result )
end

return tocrockford32

Examples

local t = require( "taptest" )
local tocrockford32 = require( "tocrockford32" )

-- https://github.com/ingydotnet/crockford-py/blob/master/tests/test_functions.py
t( tocrockford32( "foo" ), "CSQPY" )

-- https://github.com/aiq/basexx/issues/3
t( string.lower( tocrockford32( "Hello World" ) ), "91jprv3f41bpywkccg" )
t( tocrockford32( "Wow, it really works!" ), "AXQQEB10D5T20WK5C5P6RY90EXQQ4TVK44" )

t()