I need to convert a string to a unique integer, and better it's thread safe. Is that possible? How to?
Thanks.
Printable View
I need to convert a string to a unique integer, and better it's thread safe. Is that possible? How to?
Thanks.
I assume you mean convert a string to an int?
well there are multiple ways http://www.codeguru.com/forum/showthread.php?t=231054
I don't know how thread safe those are. If you want a thread safe conversion, just build one. it isn't hard, if it doesn't have floating precision.
thanks, but I didn't think that work for my case.
I mean "unique", that means the resulting integer should be unique from different strings, even from different character sequence.
I know it may be impossible, since length of string is limitless, however, integer gets maximum value.
I don't understand what you mean by unique. Maybe you can explain more or show an example in Pseudocode.
someone else might know what you're asking
It is impossible have a unique key for all strings.
Just sum all the values of string's elements (as char), or multiply, or 1st + 2nd*10 + 3rd*100 + 4th*1000... (I mean first second third as the strings first char second char when you think them as a char array. Of course starting with zero)
Are you looking to convert the string "12345" into the integer 12345, or are you simply trying to come up with an arbitrary integer for the strong "ABC" (eg, a hash function)?
If the latter, consider: There are at most 2^32-1 possibly ints (unless you use a BigInt library). There are more possible strings (bounded only by the memory of the machine, really). So by the pigeonhole principal, it's impossible to assign a different integer to each string.
However, you can design a function which assigns distinct integers to distinct strings with high probability, which is what you'd do when designing a hash function, for instance.
What you are looking for is a hash functions. There are cryptographic hash functions which have a very high probability that a string is unique (very high meaning e.g. 2^80 in the case of SHA-1). Either use one of the common hash functions (e.g. SHA-1, MD5) or google for hash algorithms, there are plenty of simpler ones.
thanks Lindley and treuss, a hash algorithm may be what I'm looking for...