Your example uses base 62. Base 64 more efficient (because it's a power of 2), well tested, produces slightly smaller results.

use MIME::Base64; $num = 123; $encoded = encode_base64(pack("V", $num), ''); $encoded =~ s/==$//; print($encoded, $/); # ewAAAA (always 6 chars) $encoded .= '=='; $num = unpack("V", decode_base64($encoded)); print($num, $/); # 123

(If you only have int16s, lowercase 'v' (in both places) will result in 3 encoded bytes.)

or even

use MIME::Base64; $num = 123; $encoded = encode_base64(pack("V", $num), ''); $encoded =~ s/A+==$//; print($encoded, $/); # ew $encoded = substr($encoded.'AAAAAA', 0, 6) . '=='; $num = unpack("V", decode_base64($encoded)); print($num, $/); # 123

In reply to Re: convert numbers to a different (arbitrary) base by ikegami
in thread convert numbers to a different (arbitrary) base by hostyle

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.