Convert base10 to base36 in perl

Possible duplicate:
What is the best way to do base36 arithmetic in Perl?

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

here is an example:

base 10 - 1234567890123 and outcome base 36 - FR5HUGNF 
+4
source share
3 answers

Try using the Math :: Base36 CPAN library for basic conversion.

+4
source

Math::Base36 source code shows how easy the conversion is:

 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 ); } 
+2
source

To do this, just write a subroutine. The code below does not check the value and assumes that the numbers to be converted are always non-negative.

If your version of Perl is not updated enough to support the state keyword, then simply declare $symbols as the variable my at the beginning 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 
0
source

Source: https://habr.com/ru/post/1438938/


All Articles