lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

Hi Ge,
yes you are completely right, in case that the difference goes in direction to MAXINT/2 this will NOT work any more... .

But my hook counter difference for sure is well below 10000, so far far away from MAXINT/2, then this works nicely... .

Thank you for your solution, you are right, your solution is somehow better as it will work also for differences above MAXINT/2 ... just generally in our software I typically in such case would also include an assert (at least in debug compile) which would alarm me if the resulting difference even is above MAXINT/4... in such case better already the "red alarm lights" should start to blink :).

For 64 bit values you fortunately really will NOT have this problem any more, at least if you think of time scale in milliseconds, which was the typical challenge in 32bit world for this problem... but in 32bit software this really is always an issue as soon as date/calender functions come up... . (if you do motor control applications with encoders, this also can quite easily happen if for fine-tune control algorithms you have the ambition to use int values with sub-micrometer encoder resolution...).

On Tue, May 4, 2021 at 9:09 PM Gé Weijers <> wrote:

On Mon, May 3, 2021 at 11:27 PM Flyer31 Test <> wrote:
sorry, how embarrassing, my ingenious code snippet had a mixup, I pressed SEND to fast,  this is correct now (assuming that the timer counts upwards...):

int getTimerDiff( int iTimerStart, int iTimerEnd){
  return iTimerEnd > iTimerStart ? iTimerEnd-iTimerStart 
                 : (unsigned int)iTimerEnd - (unsinged int)iTimerStart;

This won't quite work, because the absolute value of the difference between two integers can only be represented by an unsigned value, on a 2 complement machine the different between (-INT_MAX-1) and INT_MAX is 2*INT_MAX + 1 == UINT_MAX. The result of this subtraction will be implementation defined if the absolute difference is > INT_MAX. Implementation defined can include an overflow exception/signal.

Converting an unsigned to a signed value is also not well defined if the unsigned value is > INT_MAX.

I think this will work:

unsigned getTimerDiff(int iTimerStart, int iTimerEnd)
  return (iTimerStart <= iTimerEnd ? (unsigned)iTimerEnd - (unsigned)iTimerStart : (unsigned)iTimerStart - (unsigned)iTimerEnd);

That should work for all possible values, I think.