Convert from base64 string to long in C#

瘦欲@ 提交于 2019-12-13 14:31:57

问题


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.


回答1:


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);



回答2:


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="


来源:https://stackoverflow.com/questions/9197491/convert-from-base64-string-to-long-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!