Search code examples
c#binaryulong

Substraction of two ulong giving wrong output


DateTime epochStart = new DateTime(1970, 01, 01, 0, 0, 0, 0, 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;
}

The above c# code sometimes giving the wrong subtracted value.

For example, for following values

serverTotalSeconds = 1615184795
requestTotalSeconds = 1615184796

"r" is returning value 18446744073709551615

I am not able to understand the cause of the issue. Can somebody point out what exactly is wrong here?


Solution

  • The answer is expected. the difference is -1. which can be represented as in 8 bytes as 11111111 11111111 11111111 11111111 11111111 11111111 11111111 11111111 in binary and this is equivalent to 18446744073709551615 in decimal.

    If you use long in place of unsigned long. it will give you the expected result if you are expecting the different to be negative also.