views:

41

answers:

2

I have a string that I would like represented uniquely as an integer.

For example: A3FJEI = 34950140

How would I go about writing a EncodeAsInteger(string) method. I understand that the amount of characters in the string will make the integer increase greatly, forcing the value to become a long, not an int.

Since I need the value to be an integer, I don't need the numerical representation to be entirely unique to the string.

Maybe I can foreach through all the characters of the string and sum the numerical keycode of the character.

+3  A: 
John Kugelman
thanks for the great info! my requirements made me go with a solution that would have the same result in all versions of .net
Paul Knopf
Then use the Cryptography namespace to get a hash that won't change: http://asp.dotnetheaven.com/howto/doc/hash.aspx
Eric J.
A: 
    protected int EncodeStringAsInt(string value)
    {
        return value.ToCharArray().Sum(c => Convert.ToInt32(c));
    }
Paul Knopf
This will give a LOT of duplicate mappings compared to a real hash algorithm, e.g. BAT and TAB have the same value.
Eric J.
@Eric J - you can exclusive or (^ operator) each subsequent character than sum to avoid simple bat/tab issues, but yes, a cryptographic hash would be better.
Joel Coehoorn
@Joel: I used XOR back in the day too :-) As you say, it's better but not as good as cryptographic hash that you get from .Net. How would you express that in Linq though?
Eric J.
@Eric - with the .Aggregate() extension method.
Joel Coehoorn