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

defectivehalt picture defectivehalt · Jan 5, 2010 · Viewed 15.6k times · Source
        //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.

Answer

Michael Borgwardt picture Michael Borgwardt · Jan 5, 2010

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.