How to generate 8 bytes unique id from GUID?

后端 未结 10 1660
长情又很酷
长情又很酷 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 02:18

    In most cases bitwise XOR of both halves together is enough

    0 讨论(0)
  • 2020-12-04 02:19

    Like a few others have said, only taking part of the guid is a good way to ruin its uniqueness. Try something like this:

    var bytes = new byte[8];
    using (var rng = new RNGCryptoServiceProvider())
    {
        rng.GetBytes(bytes);
    }
    
    Console.WriteLine(BitConverter.ToInt64(bytes, 0));
    
    0 讨论(0)
  • 2020-12-04 02:20

    Yes, this will be most likely unique but since the number of bits are less than GUID, the chance of duplicate is more than a GUID - although still negligible.

    Anyway, GUID itself does not guarantee uniqueness.

    0 讨论(0)
  • 2020-12-04 02:25

    Per the Guid.NewGuid MSDN page,

    The chance that the value of the new Guid will be all zeros or equal to any other Guid is very low.

    So, your method may produce a unique ID, but it's not guaranteed.

    0 讨论(0)
提交回复
热议问题