You could naively convert all characters to ints using ord() and then concatenate them together. Don't forget to pad with zeroes to avoid problems with, eg, 654 representing either character 6 followed by character 5 followed by character 4, or character 65 followed by character 4, or character 6 followed by character 54.

For all but trivial strings this will lead to very long numbers.

So as an alternative you could treat your string as being a number in base N and simply convert it to decimal. eg, if the valid character in your input are case-insensitive ASCII letters, numbers and spaces, that's 37 "digits", so a number in base 37. Math::NumberBase is your friend here. This could still lead to very big numbers though. "AK47" is quite a small number in that system, but "Avtomat Kalashnikova 47" is a very big number.

Finally, if you're prepared to accept a *tiny* risk of two strings mapping to the same number, use a hash function. MD5 will give you a 128 bit number. If your set of inputs is small (of the order of a few thousand) then you can just take the first 32 bits of that and still generally avoid collisions, or if you have a few million inputs, take the first 64 bits.


In reply to Re: Algoritm for converting string to number? by DrHyde
in thread Algoritm for converting string to number? by DreamT

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.