[Linux-disciples] Base 10 to base 26

Stephen R Laniel steve at laniels.org
Tue Jun 6 11:00:07 EDT 2006


For silly reasons, I need to be able to convert a number to
a letter -- e.g., 26 = Z, 27 = AA, etc. Is there a quick,
easy way to do a change of base between base 10 and base 26?

Incidentally, there's a very elegant algorithm to convert
from base 10 to base 2 in the "Higher-Order Perl" book. All
integers N are equal to 2k + b, where b is either 0 or 1 and
k is a smaller integer. To figure out whether b is 0 or 1 in
the binary expansion of N, just look at whether N is an even
number or odd. If it's even, then k = 0; if it's odd, k = 1.
Then divide by 2 to get k. Division by 2 is really easy on
computers: just bit-shift the number one place to the right.
Repeat the above steps until k is 0 or 1. The full code
is below; it could probably be shortened.

But if you can help me convert to base 26, that'd be sweet.

sub decimal_to_binary {
	my $inNum = shift;
	my $k = 0;
	my $b = 0;
	if( $inNum == 1 || $inNum == 0 ) {
		return $inNum;
	}
	else {
		if( isEven( $inNum ) ) {
			$b = 0;
		}
		else {
			$b = 1;
		}
		$k = ($inNum - $b)/2;
		return decimal_to_binary($k) . $b;
	}
}

sub isEven {
	return ($_[0] % 2 == 0);
}
-- 
Stephen R. Laniel
steve at laniels.org
Cell: +(617) 308-5571
http://laniels.org/
PGP key: http://laniels.org/slaniel.key
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 191 bytes
Desc: Digital signature
Url : http://lists.bostoncoop.net/pipermail/linux-disciples/attachments/20060606/4f41b1fa/attachment.pgp


More information about the Linux-disciples mailing list