Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise operator to convert 0 to 1 and 1 to 0

In C, suppose I have an unsigned char A which can be either 0 or 1. I would like to find a bitwise logical operator that will convert A to !A.

Note: I am using this code on a GPU, where bitwise operators are very cheap compared to logical operators. i.e. XOR is much cheaper than !

like image 610
Jacko Avatar asked Nov 29 '22 10:11

Jacko


2 Answers

If by 'not' you mean send 1 to 0 and 0 to 1. you can use the XOR operator ^ to do that. If character is called c, you can write c = c ^ 1;.

like image 59
mrk Avatar answered Dec 05 '22 05:12

mrk


You should use the "logical not" operator:

A = !A;

You can also use the "bitwise not" operator, but this will make your code harder to understand since what you are doing is actually a logical not:

A = ~A;

like image 31
Étienne Avatar answered Dec 05 '22 07:12

Étienne