Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can XOR of two integers go out of bounds?

I had been studying the algorithm for finding lonely integers in an array, and here is the implementation:

int arr[] = {10, 20, 30, 5, 20, 10, 30}; int LonelyInteger = 0; for(int i=0; i< 7; i++) {     LonelyInteger = LonelyInteger ^ arr[i]; } 

The result is 5.

My question is - supposedly the integers (getting generated by the XOR operation) are too large due to this operation:

LonelyInteger ^ arr[i] 

Which leads to a potentially large integer which cannot be represented by the datatype say int in this case. My questions are:

  1. Is it even possible that XOR will generate such a large integer value that cannot be stored in the int type?
  2. If it is not possible that this can happen then is there a proof for this?
like image 774
Expert Novice Avatar asked Feb 04 '15 11:02

Expert Novice


People also ask

Can a XOR operation of two integers go out of bounds?

XOR is a bitwise operation. It does not generate integers, it generates bit patterns. The result is logically either a trap representation, or a non-trap representation of a value. It's not possible to get a "too large" result because the "too large" result would not be representable.

What does XOR do to two integers?

The XOR works by setting the bits which are set in either of one of the given numbers (0 ^ 1 = 1, 1 ^ 0 = 1) and finally taking out the common bits present in both numbers (1 ^ 1 = 0) .

Can XOR of two numbers be greater than both?

Explanation: There are only 2 pairs whose Bitwise XOR is greater than both the elements in the pair: 1) (2, 4): Bitwise XOR = 2 ^ 4 = 6, which is greater than both 2 and 4. 2) (4, 3): Bitwise XOR = 4 ^ 3 = 7, which is greater than both 4 and 3.


1 Answers

XOR will never go out of bounds because it combines bits and doesn't create new bits where no bits were set before.

The result 5 is correct. Look at the binary representation of your value and the XOR result

10    00001010 20    00010100 30    00011110  5    00000101 20    00010100 10    00001010 30    00011110 --------------       00000101 => 5 

An easy help for calculating a result of many XORed values is: The result will have a bit set where an odd number of bits are combined, no bit set for even number of bits.

If it is not possible that this can happen then is there a proof for this?

XOR is equivalent to addition without carry on the individual bits. When you add bits without carry, no overflow can happen and so the int value can't go out of bounds.

like image 185
schnaader Avatar answered Sep 22 '22 13:09

schnaader