如何生成唯一的 8 位数字? [英] How to Generate Unique Number of 8 digits?

查看:38
本文介绍了如何生成唯一的 8 位数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码生成一个 8 位唯一编号.

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

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

这段代码真的会生成一个唯一的数字,还是会再次重复相同的数字?

Does this code really generate a unique number or might it repeat the same number again?

推荐答案

GUID 不仅仅是一个随机数;它由段组成.如果在同一台计算机上生成 guid,则某些段根本不会更改.通过仅使用原始 128 位中的 64 位,您正在破坏 guid 的结构,并且很可能会破坏生成数字的唯一性.

A GUID is not just a random number; it's composed of segments. Some of the segments will not change at all if the guid is generated on the same computer. By using only 64-bits of the original 128-bits you are breaking the structure of the guid and most likely breaking the uniqueness of the generated number.

这个问题有更多关于guid唯一性的信息,查看此链接 以及有关为什么仅使用部分 guid 不好的更多信息需要一个唯一的号码.

This question has more info on uniqueness of guids, check this link as well for more info on why it's bad to use only part of a guid if you need a unique number.

如果您需要将重复限制在绝对最小值,增量计数器将为您提供所需的内容.如果您的应用程序使用多个线程或进程,则可能很难(甚至不可能)正确实现计数器.

If you need to limit duplication to an absolute minimum, an incremental counter will give you what you need. If your application is using multiple threads or processes, a counter may be hard (or even impossible) to implement correctly.

这是 guid 设计的领域,在多台机器上是唯一的.因此,如果需要跨机器的唯一性,则应使用 guid.整个指南.

This is the realm that guids were designed for, to be unique across multiple machines. So if uniqueness across machines is a requirement you should use guids. The whole guid.

这篇关于如何生成唯一的 8 位数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆