lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


> On Nov 4, 2014, at 5:39 AM, Ico Doornekamp <lua@zevv.nl> wrote:
> 
> I wrote the snippet below today to speed up the base64 encoding in my
> application using the new binary operators in Lua5.3, it might be of use for
> others.  I think the algorithm is pretty much optimal, but I'm open to any
> suggestions and improvements.
> 
> Every three input bytes are mapped to four output bytes using the binary
> operations below:
> 
>         a                   b                   c
>  +-----------------+-----------------+-----------------+
>  | 0 0 0 0 0 0 1 1 | 1 1 1 1 2 2 2 2 | 2 2 3 3 3 3 3 3 |
>  +|- - - - - -|- - + - - - -|- - - - + - -|- - - - - -|+
>  /           /              |              \           \
> /           /               |               \           \
>     a>>2     (a&3)<<4|b>>4    (b&15)<<2|c>>6      c&63
> 
> The input is padded to always be a multiple of three bytes, the output padding
> with '='s is fixed up after calculating the base64 of the padded input string.
> 
> 

Have you thought of using the new string.unpack() function to get the 3 bytes as a 64-bit integer? No idea if it would be faster, but perhaps doing multiple integer unpacks in one call would do it. Once you have the integer, peeling off 6 bits at a time is easy.

—Tim