Time elapsed between two 8-bit timestamps
https://softwareengineering.stackexchange.com/questions/305135
-
10-12-2020 - |
Question
So I have a sets of numbers representing some timings. This is how they look like:
[sec] [msec]
100 75
100 200
101 60
101 233
102 255
104 21
First column contains the elapsed seconds, and the second one the elapsed milliseconds. Values are represented using 8bit (so if the ms number is bigger than 255, the sec one gets incremented).
Now what I want to do, is to calculate the elapsed time (in milliseconds) between two inteframing values.
What I managed to do is this:
First interframe: 200 - 75 = 125ms.
Second interframe: (1 * 255 + 60) - 200 = 115ms.
Third interframe: 233 - 60 = 173ms.
Forth interframe: (1 * 255 + 255) - 233 = 277ms.
Fifth interframe: (2 * 255 + 21) - 255 = 276ms.
But this method is kinda hard to implement...
Is there any other method to find the elapsed time (in milliseconds) using another method?
Solution
Assuming we are talking about 1/256ths of a second (let's humorously call them bittiseconds), and not milliseconds, you could simply convert two values to their bittisecond representation, and then do a straight subtraction.
int ToBittiseconds(byte seconds, byte bittiseconds)
{
return seconds * 256 + bittiseconds;
}
byte v1Seconds = 100;
byte v1Bittis = 200;
byte v2Seconds = 101;
byte v2Bittis = 60;
int difference = ToBittiseconds(v2Seconds, v2Bittis) - ToBittiseconds(v1Seconds, v1Bittis);