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];

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.


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.

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);

There is no Java bitwise operations on two bytes. Your code implicitly and silently converts those bytes to a larger integer type (int), and the result is of that type as well.

You may now question the sanity of leaving bitwise operations on bytes undefined.

This was somewhere down in the answers to one of the similar questions that people have already pointed out:


Need Your Help

Remove and Replace Printed items

python python-3.x printing python-3.2

I was wondering if it was possible to remove items you have printed in Python - not from the Python GUI, but from the command prompt.

Triple equal signs return false for arrays in javascript. why?


I know that === is typically referred to as the identity operator. Values being compared must be of the same type and value to be considered equal. Then why below line returns false?