Encoding a string as an integer .NET
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 th开发者_Python百科e 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.
If these are your requirements:
- Some sort of string → integer mapping.
- Integers don't have to be unique.
Then you're in luck, because this is exactly what the GetHashCode()
method does! The MSDN page gives some sample hash codes. Note that these are completely arbitrary and can change in future versions of the CLR.
The hash code for "" is: 0x00001505, 5381
The hash code for "a" is: 0x0002B5C4, 177604
The hash code for "ab" is: 0x00596E26, 5860902
The hash code for "abc" is: 0x0B873285, 193409669
The hash code for "abd" is: 0x0B873282, 193409666
The hash code for "abe" is: 0x0B873283, 193409667
The hash code for "abcdef" is: 0x4DDB4BE2, 1306217442
The hash code for "abcdeg" is: 0x4DDB4BE3, 1306217443
The hash code for "abcdeh" is: 0x4DDB4BEC, 1306217452
The hash code for "abcdei" is: 0x4DDB4BED, 1306217453
The hash code for "Abcdeg" is: 0x941C4FC3, -1810083901
The hash code for "Abcdeh" is: 0x941C4FCC, -1810083892
The hash code for "Abcdei" is: 0x941C4FCD, -1810083891
protected int EncodeStringAsInt(string value)
{
return value.ToCharArray().Sum(c => Convert.ToInt32(c));
}
精彩评论