Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl Module to convert numbers to letter notation

Is there a perl module that will convert a number to a letter and vice versa?

For instance

1 = A 
2 = B
3 = C
...
27 = AA
28 = AB
29 = AC
...
53 = BA
54 = BB
55 = BC

So on and so forth.

like image 229
Jeffrey Ray Avatar asked Apr 03 '13 15:04

Jeffrey Ray


1 Answers

This code shows a function a2n that does what you need

use strict;
use warnings;

printf "%2s = %d\n", $_, a2n($_) for qw/ A B C AA AB AC BA BB BC /;

sub a2n {
  my $n = 0;
  $n = $n * 26 + $_ for map { ord($_) & 0x1F } split //, shift;
  $n;
}

output

 A = 1
 B = 2
 C = 3
AA = 27
AB = 28
AC = 29
BA = 53
BB = 54
BC = 55

A corresponding n2a looks like this

sub n2a {
  my ($n) = @_;
  my @a;
  while ($n > 0) {
    unshift @a, ($n-1) % 26;
    $n = int(($n-1)/26); #Edited for failing corner case
  }
  join '', map chr(ord('A') + $_), @a;
}
like image 196
Borodin Avatar answered Oct 05 '22 08:10

Borodin