cloister
Full Member
Offline
Posts: 138
Re: Millis() Overflow
Reply #1 - Mar 24th , 2009, 8:14pm
Theoretically, sure. The documentation for millis() says it returns an int. By default, that's a signed, four-byte quantity containing numbers in the range -2^31 .. 2^31-1. Millis() should, by definition, return positive quantities, meaning that only the 0..2^31-1 range is a sensible result. So, millis will overflow (well, wrap around) when it gets to 2^31-1, which is 2147483647. That many milliseconds is 24.855 days. So yes, millis() should overflow after that long. However, the normal thing that happens when a signed integer value exceeds MAX_INT (again, that same 2147483647) is that it wraps around to the negative numbers. The highest bit of signed integer values represents the sign of the number: 0 is positive (or zero), 1 is negative. So, when that 2147483647 clocks over to 2147483648, the binary representation of it trips the sign bit to 1, and presto, now the number is -2147483648. Or in other words, 2147483647 + 1 = -2147483648. Computers sure are dumb, aren't they? :) It could be, of course, that under the covers milliseconds are counted using a 64-bit value rather than a 32 bit value, or maybe Processing does something magic for you that restricts millis() to always return non-negative values. I'm not sure about that, and I'm not really motivated enough to find out to bother downloading the source code to take a look. But, if the docs are wrong and millis() is really a long int instead of a plain (4-byte) int, then the answer is still "theoretically, yes, but you won't live long enough to see it." You can work out for yourself how many days 2^63-1 milliseconds is...