Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use inverse in C

Tags:

[how to use ~ operator ]

I have a structure say Alpha. I know the value of element inside Alpha (say a) which can be 0 or 1 - I want the other element of same structure to take inverse value of Alpha.a. For example:

if Alpha.a = 1
then Alpha.b = 0

and vice versa

I have tried:

Alpha.b = ~ (Alpha.a)

But unfortunately it doesnt work - when Alpha.a is 1, Alpha.b gets set to 254

Any ideas?

Thanks and regards,

SamPrat

like image 325
samprat Avatar asked Jun 28 '11 15:06

samprat


3 Answers

In C, true is represented by 1, and false by 0. However, in a comparison, any non-false value is treated is true.

The ! operator does boolean inversion, so !0 is 1 and !1 is 0.

The ~ operator, however, does bitwise inversion, where every bit in the value is replaced with its inverse. So ~0 is 0xffffffff (-1). ~1 is 0xfffffffe (-2). (And both -1 and -2 are considered as true, which is probably what's confusing you.)

What you want is !, instead of ~.

like image 83
David Given Avatar answered Sep 20 '22 22:09

David Given


Use XOR operator:

Alpha.b = Alpha.a ^ 1;
like image 22
Prince John Wesley Avatar answered Sep 19 '22 22:09

Prince John Wesley


The ~ operator negates each individual bit. For example, assume that Alpha.a is an unsigned char. Then ~1 would read, in binary as, ~00000001, and the result would be 11111110 (again, in binary), which is the same as 254 in decimal and 0xFE in hex.

As others have suggested, use !Alpha.a or Alpha.a ^ 1.

like image 24
Lindydancer Avatar answered Sep 22 '22 22:09

Lindydancer