How to generate 8 bytes unique id from GUID?

后端 未结 10 1673
长情又很酷
长情又很酷 2020-12-04 01:21

I try to use long as unique id within our C# application (not global, and only for one session) for our events. Do you know if the following will generate an unique long id?

10条回答
  •  悲&欢浪女
    2020-12-04 01:59

    enerates an 8-byte Ascii85 identifier based on the current timestamp in seconds. Guaranteed unique for each second. 85% chance of no collisions for 5 generated Ids within the same second.

    private static readonly Random Random = new Random();
    public static string GenerateIdentifier()
    {
        var seconds = (int) DateTime.Now.Subtract(new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds;
        var timeBytes = BitConverter.GetBytes(seconds);
        var randomBytes = new byte[2];
        Random.NextBytes(randomBytes);
        var bytes = new byte[timeBytes.Length + randomBytes.Length];
        System.Buffer.BlockCopy(timeBytes, 0, bytes, 0, timeBytes.Length);
        System.Buffer.BlockCopy(randomBytes, 0, bytes, timeBytes.Length, randomBytes.Length);
        return Ascii85.Encode(bytes);
    }
    

提交回复
热议问题