Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C not operator applied to int? [duplicate]

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?

like image 689
fifamaniac04 Avatar asked Nov 27 '22 21:11

fifamaniac04


2 Answers

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.

like image 137
Andrey Mishchenko Avatar answered Dec 05 '22 05:12

Andrey Mishchenko


! is a logical operator. !expr has value 0 if expr has value non-zero. You need bitwise ~ (NOT) operator.

x = ~x;
like image 27
haccks Avatar answered Dec 05 '22 05:12

haccks