Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 881
Daniel Peñalba Avatar asked Dec 04 '22 18:12

Daniel Peñalba


2 Answers

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);
like image 76
ken2k Avatar answered Dec 31 '22 20:12

ken2k


First, convert the string to a byte[],

var array = Convert.FromBase64String(base64Hashcode);

then convert the byte array to a long

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

As has been mentioned, you'll get truncation.


The opposite direction:

var bits = BitConverter.GetBytes(@long);
var base64 = Convert.ToBase64String(bits);

Examples:

218433070285205504 : "ADCMWbgHCAM="
long.MaxValue : "/////////38="
like image 27
gͫrͣeͬeͨn Avatar answered Dec 31 '22 19:12

gͫrͣeͬeͨn