SQL BIGINT哈希匹配C#的Int64哈希 [英] SQL bigint hash to match c# int64 hash

查看:376
本文介绍了SQL BIGINT哈希匹配C#的Int64哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个完美散列alogrithim的散列一个字符串作为一个64位的int

I am trying to create a universal hashing alogrithim that hashes a string as a 64 bit int.

我能够正确地散列字符串:
SQL:

I am able to hash the strings correctly: sql:

select  
    convert
    (
        varchar(64),
        HASHBYTES
        (
            'SHA1',
            'google.com'
        ),
        2
    )

收益 BAEA954B95731C68AE6E45BD1E252EB4560CDC45

C#

    System.Security.Cryptography.SHA1 c = System.Security.Cryptography.SHA1.Create();
    System.Text.StringBuilder sb = new StringBuilder();
    byte[] b = c.ComputeHash(Encoding.UTF8.GetBytes("google.com"));
    for (int i = 0; i < b.Length;i++ )
    {
        byte by = b[i];
        sb.Append(by.ToString("x2").ToUpper());
    }

    return sb.ToString();



retruns BAEA954B95731C68AE6E45BD1E252EB4560CDC45

然而,当我转换为一个BIGINT /长值不匹配:
SQL:

However when I convert to a bigint/long the values do not match: sql:

select  
    convert
    (
        bigint,
        HASHBYTES
        (
            'SHA1',
            'google.com'
        )
    )

收益 2172193747348806725

C#:

    System.Security.Cryptography.SHA1 c = System.Security.Cryptography.SHA1.Create();
    byte[] b = c.ComputeHash(Encoding.UTF8.GetBytes("google.com"));
    return BitConverter.ToInt64(b, 0);



收益 7501998164347841210

这是如何得到这些数字的任何想法,以匹配?

Any ideas on how to get these numbers to match?

推荐答案

您SQL BIGINT取最后8个字节,而C#实现取前8个字节(并逆转他们,因为其小端运行)。

Your SQL bigint takes the last 8 bytes while the c# implementation takes the first 8 bytes (and reverses them because its running on little endian).

以数组的适当范围在C#和反向它。然后你应该罚款

Take the proper Range of the array in C# and reverse it. Then you should be fine.

做了一些代码:

System.Security.Cryptography.SHA1 c = System.Security.Cryptography.SHA1.Create();
byte[] b = c.ComputeHash(Encoding.UTF8.GetBytes("google.com"));
long value = BitConverter.ToInt64(b, 12);
value = IPAddress.HostToNetworkOrder(value);

Debug.WriteLine(value);
// writes 2172193747348806725

这篇关于SQL BIGINT哈希匹配C#的Int64哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆