### Base Conversion Utility

 on Aug 09, 2000 at 23:04 UTC Need Help??
 Category: Author/Contact Info Adam Description: This was spawned from the code in RE: RE: RE: Randomizing Unique ID? and is a subroutine that you are welcome to steal. It allows base conversions to and from base 10 to any base from 2 to 62. (less then 2 would be pointless.) It only handles non-negative integers, as I didn't feel like exploring the realm of sign bits, twos-complement, and mantissas. Enjoy. ```# Change the base representation of a non-negative integer use strict; sub GenerateBase { my \$base = shift; \$base = 62 if \$base > 62; my @nums = (0..9,'a'..'z','A'..'Z')[0..\$base-1]; my \$index = 0; my %nums = map {\$_,\$index++} @nums; my \$To = sub { my \$number = shift; return \$nums[0] if \$number == 0; my \$rep = ""; # this will be the end value. while( \$number > 0 ) { \$rep = \$nums[\$number % \$base] . \$rep; \$number = int( \$number / \$base ); } return \$rep; }; my \$From = sub { my \$rep = shift; my \$number = 0; for( split //, \$rep ) { \$number *= \$base; \$number += \$nums{\$_}; } return \$number; }; return ( \$To, \$From ); } =Example usage: my( \$ToBase62, \$FromBase62 ) = GenerateBase( 62 ); my \$UniqueID = \$ToBase62->( \$\$ ) . \$ToBase62->( time ); my \$hex = (GenerateBase(16))[0]; print \$hex->( '28' ); =cut ```
Replies are listed 'Best First'.
Re: Base Conversion Utility
by ikegami (Pope) on Oct 29, 2008 at 03:46 UTC
I had need of this recently, but the syntax is overly complicated. The use of code refs is unnecessary.
```{
my @nums = (0..9,'a'..'z','A'..'Z');
my %nums = map { \$nums[\$_] => \$_ } 0..\$#nums;

sub to_base
{
my \$base   = shift;
my \$number = shift;
return \$nums[0] if \$number == 0;
my \$rep = ""; # this will be the end value.
while( \$number > 0 )
{
\$rep = \$nums[\$number % \$base] . \$rep;
\$number = int( \$number / \$base );
}
return \$rep;
}

sub fr_base
{
my \$base = shift;
my \$rep  = shift;
my \$number = 0;
for( \$rep =~ /./g )
{
\$number *= \$base;
\$number += \$nums{\$_};
}
return \$number;
}
}

You examples becomes

```my \$UniqueID = to_base( 62, \$\$ ) . to_base( 62, time );
```print to_base( 16, 28 );

```sub GenerateBase
{
my \$base = shift;
return (
sub { to_base( \$base, \$_[0] ) },
sub { fr_base( \$base, \$_[0] ) },
);
}

Then the user has the choice of syntax at no cost.

RE: Base Conversion Utility
by Cirollo (Friar) on Aug 10, 2000 at 02:24 UTC
I don't think pi is an int.
What?? Does this mean that pi != 3??

Create A New User
Node Status?
node history
Node Type: sourcecode [id://27148]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (5)
As of 2021-01-24 06:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
The STEM quote I most wish I'd made is:

Results (262 votes). Check out past polls.

Notices?