Daniel Peñalba Daniel Peñalba - 3 months ago 24
C# Question

Convert from base64 string to long in C#

Hi I have some strings generated using the following code:

private static string CalcHashCode(byte[] data)
{
MD5CryptoServiceProvider md5Provider = new MD5CryptoServiceProvider();
Byte[] hash = md5Provider.ComputeHash(data);

return Convert.ToBase64String(hash);
}


How can I get a unique long from a encoded base64 string, I mean, the opposite operation, and then convert it to long?

private long CalcLongFromHashCode(string base64Hashcode)
{
//TODO
}


Thanks in advance.

Answer

You can't convert a base-64 string to a long (or it might be truncated if it doesn't fit, as long uses only 8 bytes)...

It's possible to convert it to a byte array (which is 'the opposite' operation):

 byte[] hash = new byte[] { 65, 66, 67, 68, 69 };
 string string64 = Convert.ToBase64String(hash);
 byte[] array = Convert.FromBase64String(string64);

If your array contains at least 8 bytes, then you could get your long value:

long longValue = BitConverter.ToInt64(array, 0);