在 Perl 中编写自定义的 base64 编码函数

4

我正在尝试编写一个自定义的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;
}

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


1
出了什么问题? - ikegami
好的,它对于我输入的每个字符串返回一个“A”的流,似乎 map { $enc[pack("B6", $_)] } @splitsixs 返回了一个常量流的“A”,但我不太明白为什么它是常量的。 - trenta3
1个回答

4

我终于成功了!我错误地尝试直接通过打包的字节索引 $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));
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接