How to Generate Unique Number of 8 digits?

后端 未结 9 985
庸人自扰
庸人自扰 2020-12-30 01:39

I am using this code to generate a 8 digit unique number.

byte[] buffer = Guid.NewGuid().ToByteArray();
return BitConverter.ToUInt32(buffer, 8).ToString();
<         


        
9条回答
  •  攒了一身酷
    2020-12-30 02:11

    Any random sequence is bound to have some collisions. It's just a matter of when. Using the birthday paradox formula, with 100,000,000 possible values (8 digits), the chance that you will have a collision with only 10,000 elements is around 40% and 99% with 30,000 elements. (see here for a calculator).

    If you really need a random sequence, you should not use a GUID for this purpose. GUIDs have very specific structure and should only be taken as a whole. It is easy enough to create a random 8 digit sequence generator. This should give you an 8 digit sequence:

     public string Get8Digits()
     {
       var bytes = new byte[4];
       var rng = RandomNumberGenerator.Create();
       rng.GetBytes(bytes);
       uint random = BitConverter.ToUInt32(bytes, 0) % 100000000;
       return String.Format("{0:D8}", random);
     }
    

    You can also take the RandomNumberGenerator and place it somewhere to avoid creating a new one everytime.

提交回复
热议问题