lua-users home
lua-l archive

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




On Mon, May 3, 2021 at 11:27 PM Flyer31 Test <flyer31@googlemail.com> 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.
 
--