Reputation: 9052
I have searched allot on google without any results I am looking for
I would like to get a numeric value from any string in C#
Ex.
var myString = "Oompa Loompa";
var numericoutput = convertStringToNumericValue(myString);
output/value of numericoutput
is something like 612734818
so when I put in another string let say "C4rd1ff InTernaT!onal is @ gr3at place#"
the int output will be something like 73572753
.
The Values must stay constant, for example so if I enter the same text again of "Oompa Loompa"
then I get 612734818
again.
I thought maybe in the way of using Font Family
to get the char index of each character, but I don't know where to start with this.
The reason for this is so that I can use this number to generate an index out of a string with other data in it, and with the same input string, get that same index again to recall the final output string for validation.
Any help or point in the right direction would be greatly appreciated
Upvotes: 0
Views: 350
Reputation: 28520
As an alternative to converting the string to it's bytes, and if a hash won't meet the requirements, here are a couple of shorter ways to accomplish getting a numeric value for a string:
string inputString = "My Test String ~!@#$%^&*()_+{}:<>?|"
int multiplier = 0;
int sum = 0;
foreach (char c in inputString)
{
sum += ((int)c) * ++multiplier;
}
The above code outputs 46026, as expected. The only difference is it loops through the characters in the string and gets their ASCII value, and uses the prefix ++ operator (Note that multiplier
is set to 0 in this case - which is also the default for int
).
Taking a cue from Damith's comment above, you could do the same with LINQ. Simply replace the foreach
above with:
sum = inputString.Sum(c => c * ++multiplier);
Finally, if you think you'll need a number larger than Int32.MaxValue
, you can use an Int64
(long
), like this:
string inputString = "My Test String ~!@#$%^&*()_+{}:<>?|"
int multiplier = 0;
long largeSum = 0;
foreach (char c in inputString)
{
largeSum += ((int)c) * ++multiplier;
}
Upvotes: 1
Reputation: 9052
Thanks to Tim
I ended up doing the following:
var InputString = "My Test String ~!@#$%^&*()_+{}:<>?|";
byte[] asciiBytes = Encoding.ASCII.GetBytes(InputString);
int Multiplier = 1;
int sum = 0;
foreach (byte b in asciiBytes)
{
sum += ((int)b) * Multiplier;
Multiplier++;
}
Obviously this will not work for 1000's of characters, but it is good enough for short words or sentences
int.MaxValue = 2 147 483 647
Upvotes: 1