If I google (7 - 12) mod 24
I get the answer 19
.
When I do it C++ I get 4294967291
uint32_t hour = (7 - 12) % 24;
// hour = 4294967291
If I try an int32_t
int32_t hour = (7 - 12) % 24;
// hour = -5
If I google (7 - 12) mod 24
I get the answer 19
.
When I do it C++ I get 4294967291
uint32_t hour = (7 - 12) % 24;
// hour = 4294967291
If I try an int32_t
int32_t hour = (7 - 12) % 24;
// hour = -5
(7 - 12) % 24
is a signed expression, and assigning it to an unsigned int
makes you see a different result
In C %
is the remainder operation so (7 - 12) % 24 = -5
unsigned(-5) = 4294967291 // since 4294967291 + 5 = 4294967296
While Google and Python uses the mathematics modulus operation, the result is 19. And 19 + 5 = 24
7-12 ans an unsigned int (uint32) gives underflow.
See also http://en.wikipedia.org/wiki/Modulo_operation for definition of the operator for negative numbers in respect to the programming language
uint32_t
is unsigned, meaning that it is restricted to positive numbers. It also means it has a larger range, since a signed byte can have values from -127 to 127, but an unsigned byte can have them from 0-255. When the unsigned int underflows, it will return a large number.
The reason that the int32_t
is returning -5 instead of 19, is because in C++ and C# the modulus operator is actually remainder.
Also see this blog psot by Eric Lippert that sums this up amazingly. Specifically...
"The % operator does not give the canonical modulus, it gives the remainder. "
Meanwhile, google gives the canonical modulus since -123 mod 4 = 1
, not -3
, as it would be in C++ or C#.
The modulus operation actually has several different possible definitions producing various results for negative numbers. C++'s definition gives a negative result (-5) for the expression (7 - 12) % 24
, and when you cast a negative value to an unsigned value you get that strange result. That value is the same as what you get if you were to do:
uint32_t x = 0;
x = x - 5;