C#和javascript中guid的相同哈希值

And*_*ews 2 javascript c# hash guid

我有一个问题,我需要能够在javascript和C#中为GUID生成相同的均匀分布的数字哈希.我想这会阻止我Guid.GetHashCode()在C#中使用,因为如果不对C#进行逆向工程,我无法重现JS中的行为.

有一种快速的方法可以在JS中使用guids/strings产生哈希吗?字符串的所有数字是否均匀分布在.NET生成的GUID中?我应该将尾随字符转换/转换为int吗?

Alb*_*nbo 5

字节显然不均匀分布.

我整理了一些代码来对.NET Guids进行采样并绘制分布图:

首先是测试代码,它创建了一百万个Guid,并计算字节数组中每个字节的不同值的数量.它将它全部输出到我在Scilab中绘制的矩阵中.

int[,] counter = new int[16, 256];
for (int i = 0; i < 1000000; i++)
{
    var g = Guid.NewGuid();
    var bytes = g.ToByteArray();
    for (int idx = 0; idx < 16; idx++)
    {
        counter[idx, bytes[idx]]++;
    }
}
StringBuilder sb = new StringBuilder();
sb.AppendLine("x = [");
for (int idx = 0; idx < 16; idx++)
{
    for (int b = 0; b < 256; b++)
    {
        sb.Append(counter[idx, b]);
        if (idx != 255)
        {
            sb.Append(" ");
        }
    }
    if (idx != 15)
    {
        sb.AppendLine(";");
    }
}
sb.AppendLine("]");

File.WriteAllText("plot.sce", sb.ToString());
Run Code Online (Sandbox Code Playgroud)

以下是分布,图表绘制了字节数组中每个位置的每个不同值的数量:

字节数组中位置0-6的值分布: 字节数组中位置0-6的值分布
字节数组中位置7的值分布:
字节数组中位置7的值分布
The value distribution for the position 8 in the byte array:
字节数组中位置8的值分布
The value distribution for the positions 9-15 in the byte array: 字节数组中位置9-15的值分布

For byte positions 0-6 and 9-15 the distribution of values seems to be even, but for byte position 7 and 8 the distribution is fairly limited.

That is, for the guid (with the beginning of the byte positions below, note strange ordering)

{1369ea05-b9f9-408b-ac7c-7ebd0f35d562}
                         1 1 1 1 1 1
 3 2 1 0  5 4  7 6  8 9  0 1 2 3 4 5
Run Code Online (Sandbox Code Playgroud)

The position 7 can take the values from 64 (0x40) to 79 (0x4F).
The position 8 can take the values from 128 (0x80) to 191 (0xBF).
The rest of the bytes are evenly distributed.

Note: The tests was run on .NET4 on a 32 bit Windows 7 machine.

Lesson: don't assume stuff, test.

答:要使用.NET Guids计算负载平衡,您可以使用上面Guid中标记为7和8的位置之外的任何部分.

问题:有人知道为什么分布不均匀分布?