首页 > 解决方案 > How to apply NXOR on 2 bits in c

问题描述

I have two bits in C language and I want o perform bitwise NXOR operator on them. I.e:

a=0,b=0 or a=1,b=1 -> NXOR(a,b)=1
a=1,b=0 or b=1,a=0 -> NXOR(a,b)=0

Any easy way to perform this? I know that the XOR operator in C is ^, but can't figure an easy way to apply the NXOR operator.

标签: c

解决方案


Make it from bitwise xor ^ and bitwise not ~. For example:

unsigned nxor(unsigned x, unsigned y) {
    return ~(x^y);
}

C only has OR, AND, NOT, and XOR. Any other bitwise operator you have to build from those four. Fortunately, you can make any bitwise operator from those four.

If you care about the high bits you can mask them off.

unsigned nxor_1bit(unsigned x, unsigned y) {
    return 1 & ~(x^y);
}

推荐阅读