How to resolve the algorithm Base64 decode data step by step in the Raku programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Base64 decode data step by step in the Raku programming language

Table of Contents

Problem Statement

See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Base64 decode data step by step in the Raku programming language

Source code in the raku programming language

my $e64 = '
VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY2
9tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=
';

my @base64map = flat 'A' .. 'Z', 'a' .. 'z', ^10, '+', '/';
my %base64 is default(0) = @base64map.pairs.invert;

sub base64-decode-slow ($enc) {
    my $buf = Buf.new;
    for $enc.subst(/\s/, '', :g).comb(4) -> $chunck {
        $buf.append: |(sprintf "%06d%06d%06d%06d", |$chunck.comb.map:
            {%base64{$_}.base(2)}).comb(8).map: {:2($_)};
    }
    $buf
}

say 'Slow:';
say base64-decode-slow($e64).decode('utf8');


# Of course, the above routine is slow and is only for demonstration purposes.
# For real code you should use a module, which is MUCH faster and heavily tested.
say "\nFast:";
use Base64::Native;
say base64-decode($e64).decode('utf8');


  

You may also check:How to resolve the algorithm URL encoding step by step in the Haskell programming language
You may also check:How to resolve the algorithm Palindrome detection step by step in the RPL programming language
You may also check:How to resolve the algorithm Hello world/Newbie step by step in the Perl programming language
You may also check:How to resolve the algorithm Haversine formula step by step in the jq programming language
You may also check:How to resolve the algorithm Sorting algorithms/Radix sort step by step in the Nim programming language