This is occurring because input
is comprised of more than four bits. If we assume that input
is a signed char
, with 8 bits (or one byte), then:
input == 15 == 0x0F == 0b00001111
As you can see, the 4 more significant bits of input
are all 0. After a bitwise NOT operation (~), we have:
~input == -16 == 0xF0 == 0b11110000
The four bits that used to be zero are now ones, and the ones are now zeros. The most significant bit in a signed variable determines its sign (0 being positive and 1 being negative). Thus, by flipping the bits the sign has been reversed. The negative number may be read as:
1 1 1 1 0 0 0 0
-128 + 64 + 32 + 16 + 0 + 0 + 0 + 0
which resolves to the -16 that was printed.
If your homework is to zero a variable using the bitwise NOT, try declaring input
as an unsigned char
to avoid having to worry about the sign bit. Then, set input
to 255
, the highest value an 8 bit variable can hold (0xFF
or 0b11111111
).