I need to xor the every single bits each other in a variable using c++
Let's consider 4-bit values a and x where their bit-representation is a = a3a2a1a0
and x = x3x2x1x0
.
We dene the masking operation "." as a.x = a3x3(xor)a2x2(xor)a1x1(xor)a0x0
.
I did a&x and find a3x3 a2x2 a1x1 a0x0
now i need to xor them but how ? is there any special way to do that ? like '&' operation ? I searched but didn't find anything..any help will be appreciated!
You'll need to shift "a and x" to do the xor of all bits.
Something like:
uint32_t a = 0xa;
uint32_t x = 0xb;
uint32_t tmp = a & x; // Bitwise AND of a and x
uint32_t res = 0;
for (int i = 0; i < 32; ++i)
{
res = res ^ (0x1 & tmp); // Only include LSB of tmp in the XOR
tmp = tmp >> 1; // Shift tmp to get a new LSB
}
cout << "Result: " << res << endl;
An alternative solution could be:
uint32_t a = 0xa;
uint32_t x = 0xb;
uint32_t tmp = a & x; // Bitwise AND of a and x
uint32_t res = 0;
while (tmp > 0)
{
if ((tmp % 2) == 1) res = (res + 1) & 0x1; // XOR operation
tmp = tmp/2; // Shift operation
}
cout << "Result: " << res << endl;