[Linux-disciples] Base 10 to base 26

Stephen R Laniel steve at laniels.org
Tue Jun 6 13:38:08 EDT 2006


On Tue, Jun 06, 2006 at 12:25:10PM -0400, Jamie Forrest wrote:
> public String decToBase26(int numberToConvert) {
>    int x;
>    StringBuffer value = "";
>    while numberToConvert > 0 {
>       x = int(((numberToConvert/26)-int(numberToConvert/26))*27.5)
>       value.append(char(x+64));
>       numberToConvert = int(numberToConvert/26)
>    }
>    return value.toString();
> }

I wrote my own in Perl; see below. It's not as elegant as it
could be, but I think it gets the job done.

I was a little confused about whether the smallest symbol --
the one corresponding to 0 -- would be 'a' or 'z'. I'm
pretty sure it would be 'a'. So then 0, 1, ..., 25, 26
would be 'a', 'b', ..., 'z', 'ba', right? 26^2 would be
'baa', etc.

This would take very little work to make more general. If
you pass in a list of admissible symbols in each numbering
scheme -- 0..10 for decimal, 0..10,a,b,c,d,e,f for hex, say
-- this function could do the work.

sub ten_to_26 {
	my $N = shift;
	my @letters = qw/a b c d e f g h i j k l m n o p q r s t u v w x y z/;
	if( $N == 0 ) {
		return $letters[0];
	}
	my $N_in_base_26 = ($N > 0) ? '' : '-';
	$N = ($N > 0 ? $N : abs($N));
	my $largest_power = floor( log($N) / log(26) );
	my $base = scalar(@letters);
	my $remainder = $N;
	for( my $exponent = $largest_power; $exponent >= 0; $exponent-- ) {
		my $coefficient = floor( $remainder/($base**$exponent) );
		$N_in_base_26 .= $letters[$coefficient];
		$remainder -= ($coefficient * ($base**$exponent));
	}
	return $N_in_base_26;
}

-- 
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/4c5bd9d9/attachment.pgp


More information about the Linux-disciples mailing list