在 perl 中编写自定义 base64 编码函数

Writing a custom base64 encoding function in perl

我正在尝试通过编写自定义 base64 编码函数来学习 perl,不幸的是,到目前为止我还没有成功。我得到的是以下内容,它不起作用,不幸的是我不知道如何继续。

sub base64($) {
  # Split string into single bits
  my $bitstring = unpack("B*", $_[0]);
  # Pack bits in pieces of six bits at a time
  my @splitsixs = unpack("(A6)*", $bitstring);
  my @enc = ("A".."Z", "a".."z", "0".."9", "+", "/");
  # For each piece of six bits, convert them to integer, and take the corresponding place in @enc.
  my @s = map { $enc[pack("B6", $_)] } @splitsixs;
  join "", @s;
}

有人可以向我解释一下我在这个转换中做错了什么吗? (请暂时搁置我不考虑填充的事实)

我终于成功了!我错误地尝试直接通过打包字节索引 $enc 中的元素,而我应该先将它们转换为整数。 您可以在下面的行中看到这一点。 我复制了整个函数,包括填充,希望它对其他人有用。

sub base64($) {
  # Split string into single bits
  my $bitstring = unpack("B*", $_[0]);
  # Pack bits in pieces of six bits at a time
  my @sixs = unpack("(A6)*", $bitstring);
  # Compute the amount of zero padding necessary to obtain a 6-aligned bitstring
  my $padding = ((6 - (length $sixs[-1]) % 6) % 6);
  $sixs[-1] = join "", ($sixs[-1], "0" x $padding);
  # Array of mapping from pieces to encodings
  my @enc = ("A".."Z", "a".."z", "0".."9", "+", "/");
  # Unpack bit strings into integers
  @sixs = map { unpack("c", pack("b6", join "", reverse(split "", $_))) } @sixs;
  # For each integer take the corresponding place in @enc.
  my @s = map { $enc[$_] } @sixs;
  # Concatenate string adding necessary padding
  join "", (@s, "=" x ($padding / 2));
}