How to Use the Bitwise Exclusive OR (XOR) Operator in C Programming

XOR is the exclusive OR operator in C programming, yet another bitwise logical operator. And to answer your most pressing question, you pronounce XOR like “zor.” It’s the perfect evil name from bad science fiction.

The XOR operation is kind of weird, but it does have its charm. In the XOR operation, bits are compared with one another, just like the & and | operators. When two bits are identical, XOR coughs up a 0. When the two bits are different, XOR spits out a 1. As usual, a program example helps explain things.

The C language XOR operator is the caret character: ^. You can find it put into action on Line 14 in It’s Exclusive OR.


#include <stdio.h>
char *binbin(int n);
int main()
 int a,x,r;
 a = 73;
 x = 170;
 printf(" %s %3d\n",binbin(a),a);
 printf("^ %s %3d\n",binbin(x),x);
 r = a ^ x;
 printf("= %s %3d\n",binbin(r),r);
char *binbin(int n)
 static char bin[9];
 int x;
 bin[x] = n & 0x80 ? '1' : '0';
 n <<= 1;
 bin[x] = '\0';

Exercise 1: Type the source code from It’s Exclusive OR into your editor. Build and run to see how the XOR operation affects binary values.

The charming thing about the XOR operation is that if you use the same XOR value on a variable twice, you get back the variable’s original value.

Exercise 2: Modify the source code from It’s Exclusive OR so that one more XOR operation takes place. Insert these three statements after Line 15:

printf("^ %s %3d\n",binbin(x),x);
a = r ^ x;
printf("= %s %3d\n",binbin(a),a);

Build and run. The output looks like this:

 01001001 73
^ 10101010 170
= 11100011 227
^ 10101010 170
= 01001001 73

Using the same XOR value of 170 turns the value 73 first into 227 and then back to 73.

Because XOR is the exclusive OR operator, some programmers refer to the standard bitwise OR operator as the inclusive OR operator.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus

Inside Sweepstakes

Win $500. Easy.