gpt4 book ai didi

c# - CombGuid 在 C# 和 SQL Server 中的差异

转载 作者:行者123 更新时间:2023-11-30 21:35:45 28 4
gpt4 key购买 nike

我正在尝试用我自己的种子生成一个 CombGuid,我需要在 C# 和 SQL Server 中生成相同的代码。

我遵循本网站所述的 CombGuid 生成理念: http://www.informit.com/articles/article.aspx?p=25862&seqNum=7

我还从以下网站借用了 C# 代码: https://github.com/richardtallent/RT.Comb

问题我无法使最后一组 Guid 在两种语言中生成相同。在 SQL Server 中,我知道它可以正常工作,因为我可以再次将 Guid 反转为 Bigint。

但在 C# 中,当我尝试反转它时,返回的值低于原始值。

我做错了什么?

代码如下:

C#:

        //create a Guid and convert it to byte
var gbytes = Guid.NewGuid().ToByteArray();

//create the last part of a Guid with a big seed
var ms = 281474967000000 + Math.Floor(DateTime.Now.Subtract(new DateTime(2018,2,21)).TotalMinutes / 10.0);
var msBytes = BitConverter.GetBytes(ms);
if (BitConverter.IsLittleEndian) Array.Reverse(msBytes);

//copy bytes for later use
var byteLen = 6;
var dbytes = new byte[byteLen];
var index = msBytes.GetUpperBound(0) + 1 - byteLen;
Array.Copy(msBytes, index, dbytes, 0, byteLen);

//replace the last part of the guid with my seed
Array.Copy(dbytes, 0, gbytes, 10, 6);
var guid = new Guid(gbytes);
//results: 6e07bc10-20d6-4cee-aefe-**ffffed7a8ec0**

T-SQL(SQL 服务器):

--this is how I generate the Guid part          
SELECT
CAST(CAST(NEWID() AS BINARY(10)) +
CAST(cast((floor(DATEDIFF(MINUTE, '2018-02-21', getdate())/10) + 281474967000000) as bigint) as BINARY(6)) AS UNIQUEIDENTIFIER)
--results: 2E2FC4CC-CA45-4C6B-81D2-**FFFFFF6BD45D**

--this is how I check its working
select format(convert(bigint, convert(binary(6), '0x' + 'FFFFFF6BD45D', 1)), '#,0')

注意事项:

在 C# 中,它生成:

6e07bc10-20d6-4cee-aefe-ffffed7a8ec0

在 T-SQL 中,它生成:

2E2FC4CC-CA45-4C6B-81D2-FFFFFF6BD45D

只注意最后一组向导。它们将与我仅在接下来的 10 分钟内更改它相同。

在 T-SQL 中,我可以毫无问题地将“FFFFFF6BD45D”反转回 BigInt。在 C# 中,反转的数字是一个较低的值。

我认为问题应该出在 byte[6](大小?),但我不明白为什么它在 SQL 中工作正常而在 C# 中却不行。

最佳答案

问题是 Math.Floor 在您的情况下返回类型是 double,所以 ms 的类型是 double . float 在内存中的表示方式不同,因此 BitConverter.GetBytes(double) 产生的结果与 BitConverter.GetBytes(long) 不同,即使值相同。所以要修复,将结果转换为 long,就像您在 SQL 查询中所做的那样(使用 as bigint):

var ms = 281474967000000 + (long)Math.Floor(DateTime.Now.Subtract(new DateTime(2018, 2, 21)).TotalMinutes / 10);            

关于c# - CombGuid 在 C# 和 SQL Server 中的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48920484/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com