【问题标题】:Algorithm to get ushort number from GUID c#从 GUID c# 获取 ushort 数的算法
【发布时间】:2018-11-29 11:55:27
【问题描述】:

如何从GUID 获取唯一的(大部分时间)ushort 数字,我尝试了下面的代码,但由于我将其转换为 ushort,所以它只是忽略了 GUID 的 LSB 十六进制值

static ushort GetId() {
            Guid guid = Guid.NewGuid();
            byte[] buffer = guid.ToByteArray();
            return BitConverter.ToUInt16(buffer, 0);
}

仅供参考:在我的代码中,我有一个 guid,我想保留相应的 ushort 号码。

【问题讨论】:

  • ushort 只有 65,536 个可能的值,你需要它有多随机/唯一?
  • 如果你想要一个唯一的 16 位值,最简单的方法是使用计数器,你可以从 128 位唯一性中借用 16 位唯一性的想法是行不通的。
  • 一个 GUID 有 2^122 或 5,316,911,983,139,663,491,615,228,241,121,400,000 个不同的可能值。 ushort 有 65,535 个。看到不同?你要求的是不可能的。而是解释您要解决的问题。
  • 为什么您希望ushort 基于 GUID?为什么不根据重复生成一个随机的ushort

标签: c# uniqueidentifier


【解决方案1】:

我尝试了下面的代码,但因为我将它转换为 ushort 所以它 只是忽略了 GUID 的 LSB 十六进制值

是的,这是正确的,并且有充分的理由,您不能将 128 位数据存储在 16 位数据中。

Name                    Length (bytes)  Contents
---------------------------------------------------------------------------------------
time_low                            4   integer giving the low 32 bits of the time
time_mid                            2   integer giving the middle 16 bits of the time
time_hi_and_version                 2   4-bit "version" in the most significant bits, followed by the high 12 bits of the time
clock_seq_hi_and_res clock_seq_low  2   1-3 bit "variant" in the most significant bits, followed by the 13-15 bit clock sequence
node                                6   the 48-bit node id

如果你想要最后 16 位(2 个字节,4 个十六进制值)只需反转数组

Array.Reverse(buffer, 0, buffer.Length);
return BitConverter.ToUInt16(buffer, 0);

注意你所做的很可疑,我真的认为你需要重新考虑你的设计

【讨论】:

  • 这是否会影响ToByteArray 返回其数据的奇怪方式(对某些人而言)? docs.microsoft.com/en-us/dotnet/api/…
  • @mjwills 很有趣,我实际上没想到,但是最后一组应该是完整的(据我所知)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-03
  • 1970-01-01
  • 2018-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多