-2

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!

hurnhu
  • 888
  • 2
  • 11
  • 30
  • What does `x3x2x1x0` mean? I assume `a3a2a1a0` is `0xA3A2A1A0`. **Edit**: got it. – YSC Dec 22 '15 at 13:38
  • The operator for xor is `^`. – Jarod42 Dec 22 '15 at 13:39
  • [If you'd searched for C++ operators](https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B) you would have found the xor operator very quickly... – Borgleader Dec 22 '15 at 13:39
  • @Jarod42 *operator ;) – YSC Dec 22 '15 at 13:39
  • 1)x3 fourth bit x2 third bit and so on.. 2)this one '^' for 2 variables I want to xor every single bits in each other in 1 variable @Borgleader I saw the page but there is only xor operation for 2 variables – user5670635 Dec 22 '15 at 13:44

2 Answers2

1

Based on your description, the final result that you're going to get is either 0 or 1, since you finished the anding, what you need is to calculate how many 1's in the binary representation of the anding result: a&x.

What you need to do is to shift the bits, one by one and calculate 1's, if the final result is odd number then the final result is 1, if even then the final result is 0.

ManKeer
  • 543
  • 2
  • 6
  • 27
0

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;
Support Ukraine
  • 42,271
  • 4
  • 38
  • 63