How to detect the difference between a wrapping counter and large negative value in C language
32-bit, c, c++, rtp, x86
Solution
Consider:
unsigned int LowerBound = -3600u, UpperBound = 4800000u;
unsigned int difference = currRTPTs - prevRTPTs;
Observe that, due to wrapping, the value of `LowerBound`, `-3600u`, will be a large positive integer. Now, when the mathematical difference (calculated without overflow) is less than -3600 by a reasonable amount, the value of `difference` will be a large integer, and it will be less than `LowerBound`. Additionally, if the difference does not become too great (in the negative direction), then `difference` will remain greater than `UpperBound`.
Similarly, if the difference is greater than 4,800,000 by a reasonable amount, the value of `difference` will be greater than `UpperBound`. If the difference does not become too much greater, then it will remain less than `LowerBound`.
Thus, in both cases, the value of `difference` when the mathematical difference is outside the desired bounds (but not by too much) is less than `LowerBound` and greater than `UpperBound`:
if (difference < LowerBound && difference > UpperBound)
printf("Delta in timestamps is outside acceptable bounds.\n");
Observe that this will fail when the mathematical difference exceeds `-3600u` (which is 4,294,967,296 - 3600) or is less than 4,800,000 - 4,294,967,296. Thus, the test works when the difference is in [-4,290,167,296, 4,294,963,696].
Problem
Apologies for my imbecility as this is my first post on this forum. I am trying to detect the difference between a wrapping unsigned 32-bit counter and a large negative Jump with the help of following code but the compiler give me error: error: comparison is always true due to limited range of data type [-Werror=type-limits] Here is my code snippet: ``` #define MAX_BACKWARD_JUMP -4294959295 //UINT_MAX - 8000 #define MIN_BACKWARD_JUMP -3600 #define MAX_FORWARD_JUMP 4800000 signed int rtpDelta; //Signed 32-bit unsigned int currRTPTs, prevRTPTs; //unsigned 32-bit rtpDelta = currRTPTs - prevRTPTs; if ((rtpDelta > MAX_BACKWARD_JUMP && rtpDelta < MIN_BACKWARD_JUMP) || (rtpDelta > MAX_FORWARD_JUMP)) { printf("Delta in Timestamps too large\n",rtpDelta); } ``` The idea here is to catch the invalid large Deltas in RTP timestamps. We have a current TimeStamp and a previous Timestamp receiving from peer RTP client. The boundary limits for invalid values of RTP Timestamps are -4294959295 < rtpDelta < -3600 that is it should throw an Error if the Delta is less than -3600 and greater than -4294959295 because the values closer to UMAX_INT will be considered as roll-over. What am I doing wrong here?