Spread the love

Write a c program to implement XOR functionality with out using XOR(^) operator

If you have your logic cleared with basic AND and OR gates, then this question is piece of cake for you.

Boolean equation for XOR gate is

XOR = AB´ + A´B

In C language, B´ (B ‘not’)  is done by ~ operator. So now logic is pretty easy you can see in below code.

 

#include <stdio.h>

inline int Xor(int x, int y)
{
	return ( (~x) & y ) | ( x & (~y) );
}

int main( )
{
	printf("%d",Xor(1,3));		// Answer would be 2 and it run successful
	
	return 0;
}

 

Suggested Reading

  1. Find position of the only set bit
  2. Write a Macro’s Set,clear and toggle n’th bit using bit wise operators?
  3. Count number of 1s in given binary number