2

我有一种情况是从另一个整数创建一个 16 位数字。它应该像信用卡号码。那么我们的场景是,如果该用户 ID 是 1 或 2,则应将其散列为 16 位字符串(数字)。所以 16 位应该是唯一的 1 我尝试了 .NET 内置函数,如生成哈希等。

这并没有帮助我找到完美的解决方案

4

2 回答 2

1

也许你可以使用这个:

string SixteenDigitHash(int value)
{
   var rnd = new Random(value);
   StringBuilder sb = new StringBuilder(16);
   sb.Append(rnd.Next(1,10)); // first digit 1..9
   for (int i=1; i<16; i++)
   {
     sb.Append(rnd.Next(0,10)); // other digits 0..9
   }

   return sb.ToString();
}

它用于Random生成(伪)随机数,但使用 value-to-hash 作为种子,因此它总是为给定值生成相同的序列,为不同的值生成不同的序列。

一个问题:对于不同版本的框架,顺序不保证是相同的。也许你应该使用你自己的 Random 类的实现,这样你就知道序列是稳定的。

于 2013-07-18T07:52:20.630 回答
1

不确定您期望有多少用户,但此代码生成 16 位整数,并且使用从 1 到 100 的数字没有重复:

Imports System.Security.Cryptography

    Dim sha As New SHA1CryptoServiceProvider()
    Dim IntList As New List(Of ULong)
    For I = 1 To 100000
        'Need a byte array for the ComputeHash method
        Dim data() As Byte = BitConverter.GetBytes(I)
        If BitConverter.IsLittleEndian Then Array.Reverse(data)
        'Store the 160 bit hash in a byte array
        Dim result As Byte() = sha.ComputeHash(data)
        'Bitconverter's result can be too long, so by taking the first 16 digits _
         of the results that are too long, and padding the rest to the right with _
        0's we end up with unique 16 digit integers
        Dim HashInt As ULong = ULong.Parse(BitConverter.ToUInt64(result, 0).ToString.PadRight(16, "0"c).Substring(0, 16))
        'Using a list to hold the hash's is just to confirm that each one is unique. _
        for the your purposes I would suggest a dictionary(of integer, ulong)
        If Not IntList.Contains(HashInt) Then
            IntList.Add(HashInt)
        End If
    Next

更新:修改代码以显示它将产生 100000 个唯一哈希。IntList.Count = 100000。

对于最终小于 16 位的结果,我用 0 填充末尾。这只是方便。通过将 BitConverter.ToUInt64 结果放入字符串中,您可以将 0 插入您喜欢的任何位置。

于 2013-07-17T07:47:08.517 回答