Perl字符串到Base36

时间:2012-09-26 21:31:15

标签: perl

如何在perl中将字符串转换为base36(0-9,a-z)?

我想用一对一的地图将IP地址转换为base36,所以我可以在网址中使用它们。

127.0.0.1 === string ==> 127000000001 === base36 ==>

72.98.234.11 === string ==> 072098234011 === base36 ==>

2 个答案:

答案 0 :(得分:4)

基础10不够好吗?这给出了[0-4294967295]中的数字(1到10位数)。这比我们从你的方式(1到8位)得到的时间略长。

$ perl -E'say unpack "N", pack "C4", split /\./, $ARGV[0]' 127.0.0.1
2130706433

$ perl -E'say unpack "N", pack "C4", split /\./, $ARGV[0]' 72.98.234.11
1214441995

完全可逆:

$ perl -E'say join ".", unpack "C4", pack "N", $ARGV[0]' 2130706433
127.0.0.1

$ perl -E'say join ".", unpack "C4", pack "N", $ARGV[0]' 1214441995
72.98.234.11

您可以使用CPAN上的任意数量的模块将该数字转换为10以外的其他基数。

base 10: 1-10 digits
base 16: 1-8 digits    # Can be done very efficiently
base 32: 1-7 digits    # Can be done very efficiently
base 36: 1-7 digits
base 62: 1-6 digits
base 64: 1-6 digits    # Can be done very efficiently

基地16:

sub pack_ip { sprintf "%X", unpack "N", pack "C4", split /\./, $_[0] }

sub unpack_ip { join ".", unpack "C4", pack "N", hex $_[0] }

Base 64 :(这应该非常快。即使移植到C也会更快。)

my @syms = ('0'..'9', 'A'..'Z', 'a'..'z', '_', '-');
my %syms = map { $sym[$_] => $_ } 0..$#syms;

sub pack_ip {
   my $num = unpack "N", pack "C4", split /\./, $_[0];
   my $base64 = join '', @syms[
      ($num >> 30) & 0x3F,
      ($num >> 24) & 0x3F,
      ($num >> 18) & 0x3F,
      ($num >> 12) & 0x3F,
      ($num >>  6) & 0x3F,
      ($num >>  0) & 0x3F,
   ];
   $base64 =~ s/^A+(?!\z)//;
   return $base64;
}

sub unpack_ip {
   my $num;
   $num = ($num << 6) | $sym{$_}
      for split //, $_[0];
   return join ".", unpack "C4", pack "N", $num;
}

答案 1 :(得分:-1)

为什么不使用base 16,因为那基本上就是IP地址了?

sub ip_to_hex {
  join('', map { sprintf('%02x', $_) } split(/\./, shift));
}

sub hex_to_ip {
  join('.', map { hex($_) } shift =~ m/([0-9a-f]{2})/g);
}

say ip_to_hex('127.0.0.1');    # 7f000001
say ip_to_hex('72.98.234.11'); # 4862ea0b
say hex_to_ip('4862ea0b');     # 72.98.234.11