The bitwise negation will not result in 0101
. Note that an int contains at least 16 bits. So, for 16 bits, it will generate:
a = 0000 0000 0000 1010
~a = 1111 1111 1111 0101
So we expect to see a large number (with 16 bits that would be 65'525), but you use %d
as format specifier. This means you interpret the integer as a signed integer. Now signed integers use the two-complement representation [wiki]. This means that every integers where the highest bit is set, is negative, and furthermore that in that case the value is equal to -1-(~x)
, so -11
. In case the specifier was %u
, then the format would be an unsigned integer.
EDIT: like @R. says, %d
is only well defined for unsigned integers, if these are in the range of the signed integers as well, outside it depends on the implementation.