4

Possible Duplicate:
What’s the best way to do base36 arithmetic in Perl?

Hello is it possible to convert numbers from a base-10-to-base-36-conversion with perl script?

here's an example :

base 10 - 1234567890123 and outcome
base 36 - FR5HUGNF
Community
  • 1
  • 1
user1729072
  • 53
  • 1
  • 3

3 Answers3

4

Try using Math::Base36 CPAN library for base conversion.

Jean
  • 21,665
  • 24
  • 69
  • 119
3

Poking around the Math::Base36 source code shows how easy it is to enact the conversion:

sub encode_base36 {
    my ( $number, $padlength ) = @_;
    $padlength ||= 1;

    die 'Invalid base10 number'  if $number    =~ m{\D};
    die 'Invalid padding length' if $padlength =~ m{\D};

    my $result = '';
    while ( $number ) {
        my $remainder = $number % 36;
        $result .= $remainder <= 9 ? $remainder : chr( 55 + $remainder );
        $number = int $number / 36;
    }

    return '0' x ( $padlength - length $result ) . reverse( $result );
}
Zaid
  • 36,680
  • 16
  • 86
  • 155
1

It is quite straightforward to write a subroutine to do this. The code below does no value checking and assumes the numbers to be converted are always non-negative

If your version of Perl isn't sufficiently up-to-date to support the state keyword, then just declare $symbols as a my variable at the head of the program

use strict;
use warnings;

use feature 'state';

print base36(1234567890123);

sub base36 {
  my ($val) = @_;
  state $symbols = join '', '0'..'9', 'A'..'Z';
  my $b36 = '';
  while ($val) {
    $b36 = substr($symbols, $val % 36, 1) . $b36;
    $val = int $val / 36;
  }
  return $b36 || '0';
}

output

FR5HUGNF
Borodin
  • 126,100
  • 9
  • 70
  • 144