I have
int x = 5;
printf("%d", x); //i get 5... expected
x = !x;
printf("%d", x);// i get 0... hmm
5 in binary is: 0101
if we apply the inverse to each bit, we should get 1010, but !
is not necessarily an inverter, it's a logical operator. Why do i get a 0
?
is the reason that, in C, a positive number is treated as true and so !
-ing it would result in 0?
is this compiler specific?
The not (!
) operator returns either 0
or 1
, depending on whether the input is non-zero or 0
respectively.
If you are looking for a bitwise negation, try ~x
.
!
is a logical operator. !expr
has value 0
if expr
has value non-zero. You need bitwise ~
(NOT) operator.
x = ~x;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With