tags:

views:

194

answers:

3

I want to say that is is self learning.

We have two integers. I want to get a third element that it is equal to XOR between the two integers, but with the constraint. OK, let me give an example to be more clear.

int x is, let's say, is 10   `x = 10 //Binary 1010`  and `int y = 9 //Binary 1001`   

int t = x^y,  where ^ is an operator that is defined as described below. 

But the first bit in x should be XORed with the second bit of y and be stored as first bit in t and the second bit in x XORed with the first bit in y and stored in the second bit in t and so on.
The result should thus be:

t = x^y = 1100

I hope you understand the problem. If not, I will try to clarify.

A: 

What the other answerers said. If you want to reverse it, use a bitwise not:

t = ~(x ^ y)

Though of course it might not be quite what you want given the size of your integer, in which case you can then and it with a bitmask. E.g., if you want 4 bits:

t = (~(x ^ y)) & 15;

Wevah
+2  A: 

Is this what you mean?

1 0 1 0
 x   x
1 0 0 1

=> t = 1 xor 0 + 0 xor 1 + 1 xor 1 + 0 xor 0 = 1100 (+ = concat)

Try this:

int getBit(int num, int bitNum)
{
   --bitNum;
    return (num & (1 << bitNum)) > 0 ? 1 : 0;
}

int main()
{
    int x = 10, y = 9;
    int size = 4;

    int t = 0;
    for ( int i = 0; i < size; ++i )
        if ( i % 2 == 0 )
            t |= (getBit(x, size - i) ^ getBit(y, size - i - 1)) << (size - i - 1);
        else
            t |= (getBit(x, size - i) ^ getBit(y, size - i + 1)) << (size - i - 1);

    cout << t;

    return 0;
}

You need to know the "size" of the numbers, which is the position of the most significant bit, or log2(number) + 1.

IVlad
yes it is it what i want
+5  A: 

but first bit in x should be xored second bit of y and be stored as first bit int t and second bit int x to > first bit in y and stored second bit in t and so on

...so this isn't really a question about xor, it's a question about how to swap each pair of bits of y.

You can do this using something like this:

  • (y & 0xaaaaaaaa) >> 1 selects the most significant (leftmost) bit of each pair of bits, and moves them all right by one bit. (0xaaaaaaaa is 101010....101010 in binary.)
  • (y & 0x55555555) << 1 selects the least significant (rightmost) bit of each pair, and moves them all left by one bit. (0x55555555 is 010101....010101 in binary.)
  • So: y_pairwise_bit_swapped = ((y & 0xaaaaaaaa) >> 1) | ((y & 0x55555555) << 1) will perform the swapping.

Then t = x ^ y_pairwise_bit_swapped.

(Adjust the constants as necessary for your maximum required bit width, obviously.)

Matthew Slattery