good chemistry is complicated,and a little bit messy -LW PerlMonks

### Re: Algoritm for converting string to number?

by DrHyde (Prior)
 on Aug 23, 2011 at 09:50 UTC ( #921855=note: print w/replies, xml ) Need Help??

in reply to Algoritm for converting string to number?

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.

• Comment on Re: Algoritm for converting string to number?

Create A New User
Node Status?
node history
Node Type: note [id://921855]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (12)
As of 2018-03-23 13:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
When I think of a mole I think of:

Results (293 votes). Check out past polls.

Notices?