在 C# 中将 base64 字符串转换为 long

发布于 2025-01-03 07:21:03 字数 459 浏览 3 评论 0原文

您好,我使用以下代码生成了一些字符串:

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

    return Convert.ToBase64String(hash);
}

如何从编码的 Base64 字符串中获取唯一的 long,我的意思是相反的操作,然后将其转换为 long?

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

提前致谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

深爱成瘾 2025-01-10 07:21:03

您无法将 base-64 字符串转换为 long(或者如果不合适,它可能会被截断,因为 long 仅使用 8 个字节)...

可以将其转换为字节数组(这是“相反”操作):

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

如果您的数组至少包含 8 个字节,那么您可以获得 long 值:

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

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);
蝶…霜飞 2025-01-10 07:21:03

首先,将字符串转换为 byte[],

var array = Convert.FromBase64String(base64Hashcode);

然后将字节数组转换为 long

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

正如前面提到的,您将得到截断。


相反方向:

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

示例:

218433070285205504 : "ADCMWbgHCAM="
long.MaxValue : "/////////38="

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="
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文