Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

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?

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://921855]
[choroba]: well, beer is good here, surprisingly
[choroba]: also, I discovered several vegan/vegetarian restaurants, so I can avoid meat
[LanX]: ha ha ... happy Czech :)
[choroba]: been to the War Remnants Museum, too. Quite a brutal experience
[choroba]: but still, small-talk about smuggling guns and how Trump is great with US expats isn't my cup of tea
[LanX]: brutal beer?
[LanX]: met a Canadian yesterday, he suggested building a wall and let the US pay for it

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (6)
As of 2017-02-26 04:37 GMT
Find Nodes?
    Voting Booth?
    Before electricity was invented, what was the Electric Eel called?

    Results (371 votes). Check out past polls.