You’ve already hinted at overflow, and in fact this is exactly what’s happening here. You already know what u
and u-1
are (255 and 254 respectively), so let’s multiply those together. This gives us 64770, or in binary:
64770 = 1111 1101 0000 0010
This result is 16 bits wide, but we’re storing it in a uint8
which is only 8 bits wide. It is therefore truncated to the 8 least significant bits. Mathematically, this is equivalent to performing 64770 mod 2^8 or 64770 mod 256. Programatically, it’s equivalent to performing 64770 & (1 << 7)
or 64770 & 256
:
64770 = 1111 1101 0000 0010
256 = 1111 1111
64770 & 256 = 0000 0000 0000 0010 = 2
However you chose to imagine this operation, the result is 2.