Home > Mobile >  Values subtraction in the time calculation
Values subtraction in the time calculation

Time:06-26

Having such a bit of code:

DWORD time1 = 0xFFFFFFFC;
DWORD time2 = 0x0000000B; //11 dec
DWORD time3 = 0x0000000D; //13 dec
DWORD time4 = 0x0000000F; //15 dec

swprintf_s(g_msgbuf, L"delta1: %i, %u\n", time2 - time1, time2 - time1);
OutputDebugString(g_msgbuf);

swprintf_s(g_msgbuf, L"delta2: %i, %u\n", time3 - time1, time3 - time1);
OutputDebugString(g_msgbuf);

swprintf_s(g_msgbuf, L"delta3: %i, %u\n", time4 - time1, time4 - time1);
OutputDebugString(g_msgbuf);

if ((time2 - time1) == 15)
    OutputDebugString(L"equal\n");
else
    OutputDebugString(L"not equal\n");

I'm getting the following output:

delta1: 15, 15
delta2: 17, 17
delta3: 19, 19
equal
  1. Can someone please explain me the output results: 15, 17, 19? (Where are the values coming from)
  2. Since I'm implementing a simple game loop and have to measure a delta time between two frames. The code above just simulates so called "wrap around" problem (Yes, i'm using the timeGetTime function and PLEASE DON'T tell me to use another, newer/better time function!) when we deal with subtraction when the second number(second time) is bigger than first number(first time) thus in theory resulting in just negative number BUT as we can see the values 15, 17, 19 seems to be just what I have to get - the absolute delta time(minus 1) between two frames even if there was that "wrap around" and this is my second question - in the case above can i rely on that implicit compiler behavior and just forget about the "wrap around" problem since the resulting values seems to be correct(mins 1)?

CodePudding user response:

Unsigned arithmetic is performed modulo the max value the type can hold plus one.

Therefore

0x0000000B - 0xFFFFFFFC

with 4 byte unsigned types such as DWORD yields the same result as

0x0000000B - (0xFFFFFFFC   4 - 4)

or

0x0000000B   4 - (0xFFFFFFFC   4)

or (using the fact that the brackets are 0 modulo the max value DWORD can hold 1)

0x0000000B   4 - 0x00000000

which is 15 (or 0x0F).

Similar for the other differences.

You can rely on this behaviour, see the Overflows section of the Arithmetic operators page on cppreference.com

  • Related