c# - 如何从 GUID 生成 8 字节的唯一 ID?

标签 c# .net

我尝试在我们的 C# 应用程序(不是全局的,并且只用于一个 session )中为我们的事件使用 long as unique id。您知道以下是否会生成唯一的长 id 吗?

public long GenerateId()
{
 byte[] buffer = Guid.NewGuid().ToByteArray();
 return BitConverter.ToInt64(buffer, 0);
}

为什么不直接使用GUID呢?我们认为 8 个字节长就足够了。

最佳答案

不,不会。正如 Raymond Chen 的博客上多次强调的那样,GUID 被设计成作为一个整体是唯一的,如果你只剪掉它的一部分(例如,从它的 128 个字节中只取出 64 个字节),它将失去它的(伪)唯一性保证.


Here它是:

A customer needed to generate an 8-byte unique value, and their initial idea was to generate a GUID and throw away the second half, keeping the first eight bytes. They wanted to know if this was a good idea.

No, it's not a good idea. (...) Once you see how it all works, it's clear that you can't just throw away part of the GUID since all the parts (well, except for the fixed parts) work together to establish the uniqueness. If you take any of the three parts away, the algorithm falls apart. In particular, keeping just the first eight bytes (64 bits) gives you the timestamp and four constant bits; in other words, all you have is a timestamp, not a GUID.

Since it's just a timestamp, you can have collisions. If two computers generate one of these "truncated GUIDs" at the same time, they will generate the same result. Or if the system clock goes backward in time due to a clock reset, you'll start regenerating GUIDs that you had generated the first time it was that time.


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 the following will generate an unique long id?

为什么不直接使用计数器呢?

关于c# - 如何从 GUID 生成 8 字节的唯一 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5678177/

相关文章:

.net - 按实现类型查找 Ninject 绑定(bind)

c# - 如何检索 Azure 表中的顶行

c# - 在母版页的代码后面更改样式表

用于订阅/发布 MQTT(真正的小型消息代理)的 C# 客户端库

.net - 从 WCF 服务获取实体

c# - 使用代码优先使用实体​​框架检查表是否为空

c# - 保证信号量顺序?

c# - 在文本文件中加载和访问模板变量

c# - 从原始 ECG 信号中提取心率的算法

c# - 在 c# dll 和 c++ dll 之间传递字符串变量作为引用