From milliseconds to hour, minutes, seconds and milliseconds
Good question. Yes, one can do this more efficiently. Your CPU can extract both the quotient and the remainder of the ratio of two integers in a single operation. In <stdlib.h>
, the function that exposes this CPU operation is called div()
. In your psuedocode, you'd use it something like this:
function to_tuple(x):
qr = div(x, 1000)
ms = qr.rem
qr = div(qr.quot, 60)
s = qr.rem
qr = div(qr.quot, 60)
m = qr.rem
h = qr.quot
A less efficient answer would use the /
and %
operators separately. However, if you need both quotient and remainder, anyway, then you might as well call the more efficient div()
.
Here is how I would do it in Java:
int seconds = (int) (milliseconds / 1000) % 60 ;
int minutes = (int) ((milliseconds / (1000*60)) % 60);
int hours = (int) ((milliseconds / (1000*60*60)) % 24);