5

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 !

1
  • 1
    what do you mean with "!A"? That doesnt make any sense, there is no inversion of a character.
    – specializt
    Commented Jan 17, 2015 at 14:19

3 Answers 3

14

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;.

4
  • 1
    Also, if I treat a true boolean expression as a char, is that char equal to 1 ? i.e. char test = (A == 1); Is test equal to 1 in this case?
    – Jacko
    Commented Jan 17, 2015 at 14:05
  • @Jacko Yes it is. Also, you should use A = !A; from another answer. c = c ^ 1 will only invert the first bit of the char and I have ho idea why would you need to do it. Commented Jan 17, 2015 at 14:59
  • Thanks, HolyBlackCat. But, if c == 0, then c^1 will equal 1. And if c ==1, then c^1 will equal 0. So this is what I am looking for.
    – Jacko
    Commented Jan 17, 2015 at 22:14
  • Thank you , saadtaame. Very helpful.
    – Jacko
    Commented Jan 17, 2015 at 22:16
5

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;

3
  • 1
    I've neutralised the downvote; I thought your answer was intuitive!
    – Poriferous
    Commented Jan 17, 2015 at 14:19
  • Thanks. I am trying to avoid logical operators. I have added this to the question.
    – Jacko
    Commented Jan 17, 2015 at 22:16
  • I don't know about other languages but in C#, you get negative numbers if you use "~" and error if you use "!".
    – Raja
    Commented Dec 29, 2021 at 23:04
1

XOR assignment with 1 is handy if you just need a flag to toggle repeatedly.

$ clang -x c -include stdio.h -pipe -o meh - <<\EOF && ./meh
int main(int argc, char **argv) {
    unsigned char x = '\0';
    for (int n = 0; n <= 50; n++) printf("%d", x ^= 1);
    return 0;
}
EOF

101010101010101010101010101010101010101010101010101

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.