Assuming int
is 32 bit on your machine then 7
is 0b00000000000000000000000000000111
and ~7
becomes 0b11111111111111111111111111111000
which is -8
.
Background
For signed values the most significant bit is used to determine if the value is negative or not. When the MSB is set, the value is negative.
In addition to that (char) 0b10000000
is -128 and (char) 0b11111111
is -1.
So counting works as follows:
0b10000000 0b10000001 [...] 0b11111111 0b00000000 [...] 0b01111111
-128 -127 [...] -1 0 [...] 127
That is the reason why you will get -128 when you count 127+1 and try to store that in a char
.