Reputation: 2021
A really simple question:
I am doing a simple thing. I have few string
like:
string A = "usd";
And I want to get the hashcode in C#:
int audusdReqId = Convert.ToInt32("usd".GetHashCode());
Now how could I convert the 32-bit integer audusdReqId
back to the string
"usd"?
Upvotes: 4
Views: 12204
Reputation: 6890
The purpose of the hashcode/hash function is that it has to be one way and that it cannot be converted back to the original value.
There are good reasons as to why this is so. A common usage would be password storage in a database for example. You shouldn't know the original value(the plain text password) and that is why you would normally use a hashcode to encode it one way.
There are also other usages as storing values to hashsets etc.
Upvotes: 4
Reputation: 141668
You cannot. A hash code does not contain all of the necessary information to convert it back to a string. More importantly, you should be careful what you use GetHashCode
for. This article explains what you should use it for. You can't even guarantee that GetHashCode
will return the same thing in different environments. So you should not be using GetHashCode
for any cryptographic purposes.
If you are trying to create a binary representation of a string, you can use
var bytes = System.Text.Encoding.UTF8.GetBytes(someString);
This will give you a byte[]
for that particular string. You can use GetString
on Encoding to convert it back to a string:
var originalString = System.Text.Encoding.UTF8.GetString(bytes);
If you are trying to cryptographically secure the string, you can use a symmetric encryption algorithm like AES as Robert Harvey pointed out in the comments.
Upvotes: 17