Re: [exim] Base62 to Decimal

Αρχική Σελίδα
Delete this message
Reply to this message
Συντάκτης: Phil Pennock
Ημερομηνία:  
Προς: Grant Peel
Υ/ο: exim-users
Αντικείμενο: Re: [exim] Base62 to Decimal
On 2011-12-30 at 11:26 -0500, Grant Peel wrote:
> Does anyone have a simple perl snippett that accepts base62 code (as
> in exim mail IDs) and converts it to decimal ?


I'm assuming you're after decoding the time from the first part of the
message id, per "3.4 Message identification", and are not concerned
about portability to MacOS?

The alphabet is:
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz

This is optimised for clarity rather than performance:
----------------------------8< cut here >8------------------------------
#!/usr/bin/perl
use warnings;
use strict;

use constant BASE62DICT => join('', 0..9, 'A'..'Z', 'a'..'z');

sub base62_to_num {
    my @input = split(//, $_[0]);
    my $result = 0;
    foreach my $b62digit (@input) {
        my $offset = index BASE62DICT, $b62digit;
        if ($offset == -1) {
            die "exception/base62_to_num: invalid base62 digit: $b62digit";
        }
        $result *= 62;
        $result += $offset;
    }
    return $result;
}


foreach my $arg (@ARGV) {
    print $arg, "\t", base62_to_num($arg), "\n";
}
----------------------------8< cut here >8------------------------------


Taking an id from your message: 1RgfJa-0004Tx-OG
% ./b62.pl 1RgfJa 0004Tx OG
1RgfJa    1325262498
0004Tx    17233
OG    1504
% time_render 1325262498
2011-12-30T11:28:18 -0500 (Fri Dec 30 11:28:18 2011 EST)


That looks to me like it's returning sane results.

My Perl is rusty, I've been mostly in Python for the past few years.
I'm sure there are more performant perlgolf hacks possible. I don't
care. :)
--
https://twitter.com/syscomet