Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the xor operator on two bytes produce an int?

        //key & hash are both byte[]         int leftPos = 0, rightPos = 31;         while(leftPos < 16) {             //possible loss of precision. required: byte, found: int             key[leftPos] = hash[leftPos] ^ hash[rightPos];             leftPos++;             rightPos--;         } 

Why would a bitwise operation on two bytes in Java return an int? I know I could just cast it back to byte, but it seems silly.

like image 866
defectivehalt Avatar asked Jan 04 '10 23:01

defectivehalt


People also ask

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) . Now, the result x ^ y would be (x | y) - (x & y) = (01010001 - 01000000) = 00010001 .

What does XOR do on integers?

XOR is defined as exclusive or for two integers say a and b. To find XOR, we will first find the binary representation of both a and b. Lets do this also by example. Suppose a = 7 and b = 10.

What is the output of XOR operator when both bits are set?

The result of XOR is 1 if the two bits are different.


2 Answers

Because the language spec says so. It gives no reason, but I suspect that these are the most likely intentions:

  • To have a small and simple set of rules to cover arithmetic operations involving all possible combinations of types
  • To allow an efficient implementation - 32 bit integers are what CPUs use internally, and everything else requires conversions, explicit or implicit.
like image 109
Michael Borgwardt Avatar answered Oct 26 '22 20:10

Michael Borgwardt


If it's correct and there are no value that can cause this loss of precision, in other words : "impossible loss of precision" the compiler should shut up ... and need to be corrected, and no cast should be added in this :

byte a = (byte) 0xDE;  byte b = (byte) 0xAD; byte r = (byte) ( a ^ b); 
like image 27
RzR Avatar answered Oct 26 '22 20:10

RzR