Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is slightly different, but I think clearly illustrates the logic involved. I'm working on some MSP430 code in C, and have a timestamp struct very similar to timeval, but with nsecs instead of usecs.</p> <p>This code keeps everything positive, so unsigned ints would work fine, and avoids overflows (I think). It also doesn't modify the timestamps/timevals being passed in, except the result of course.</p> <pre><code>typedef struct timestamp { int32_t secs; int32_t nsecs; } timestamp_t; int timestamp_sub(timestamp_t * x, timestamp_t * y, timestamp_t * result){ // returns 1 if difference is negative, 0 otherwise // result is the absolute value of the difference between x and y negative = 0; if( x-&gt;secs &gt; y-&gt;secs ){ if( x-&gt;nsecs &gt; y-&gt;nsecs ){ result-&gt;secs = x-&gt;secs - y-&gt;secs; result-&gt;nsecs = x-&gt;nsecs - y-&gt;nsecs; }else{ result-&gt;secs = x-&gt;secs - y-&gt;secs - 1; result-&gt;nsecs = (1000*1000*1000) - y-&gt;nsecs + x-&gt;nsecs; } }else{ if( x-&gt;secs == y-&gt;secs ){ result-&gt;secs = 0; if( x-&gt;nsecs &gt; y-&gt;nsecs ){ result-&gt;nsecs = x-&gt;nsecs - y-&gt;nsecs; }else{ negative = 1; result-&gt;nsecs = y-&gt;nsecs - x-&gt;nsecs; } }else{ negative = 1; if( x-&gt;nsecs &gt; y-&gt;nsecs ){ result-&gt;secs = y-&gt;secs - x-&gt;secs - 1; result-&gt;nsecs = (1000*1000*1000) - x-&gt;nsecs + y-&gt;nsecs; }else{ result-&gt;secs = y-&gt;secs - x-&gt;secs; result-&gt;nsecs = y-&gt;nsecs - x-&gt;nsecs; } } } return negative; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload