Negative numbers are represented in the two's complement form, that is, the binary representation of -100
is
(2**32 - 100).toString(2) = 11111111111111111111111110011100
adding 0xff
gives 10011100
, which is 156
.
The modulus operation %
is defined as
IF a % b == r THEN a == b * q + r for some q
There are always two choices for q
and r
, with a positive and a negative remainder. For example, with 7 % 3
,
7 = 3 * 2 + 1
7 = 3 * 3 - 2
The same for negative numbers, -7 % 3
:
-7 = 3 * (-2) - 1
-7 = 3 * (-3) + 2
For positive numbers, all languages pick the positive remainder. For negative numbers, the choice is different from language to language. e.g. in python, the remainder is always positive, so
-7 % 3 = 2 # python
Javascript picks the negative remainder, so in JS
-7 % 3 = -1 // javascript
Similarly, for -100 % 256
-100 = 256 * ( 0) - 100
-100 = 256 * (-1) + 156
In python the remainder would be 156
(and thus match the & FF
), in javascript it's -100
.