两个 ulong 相减给出错误输出

问题描述

DateTime epochStart = new DateTime(1970,01,DateTimeKind.Utc);
TimeSpan currentTs = DateTime.UtcNow - epochStart;
ulong serverTotalSeconds = Convert.ToUInt64(currentTs.TotalSeconds);
ulong requestTotalSeconds = Convert.ToUInt64(requestTimeStamp);
ulong r = (serverTotalSeconds - requestTotalSeconds);
if (r > requestMaxAgeInSeconds)
{
     return true;
}

上面的 c# 代码有时会给出错误的减去值。

例如,对于以下值

serverTotalSeconds = 1615184795
requestTotalSeconds = 1615184796

"r" is returning value 18446744073709551615

我无法理解问题的原因。有人能指出这里到底有什么问题吗?

解决方法

答案在意料之中。差异是-1。它可以用 8 个字节表示为二进制的 11111111 11111111 11111111 11111111 11111111 11111111 11111111 11111111,这相当于十进制的 18446744073709551615

如果您使用 long 代替 unsigned long。如果您期望不同的结果也是负数,它会给您预期的结果。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...