Search code examples
javabytexor

XOR operation on bytes


I am trying to understand the working of XOR on bytes

    byte byte1 = (byte)0x00;
    byte byte2 = (byte)0x80;
    int x = ((byte1^byte2));
    System.out.println("Value of X is "+x);
    int x1 = ((byte1^byte2)&0xff);
    System.out.println("Value of X1 is "+x1);

The output displayed is:

   Value of X is -128
   Value of X1 is 128

Here I am trying to perform XOR on byte1 and byte2 and then mask it with 0xff. byte1^byte2 gives me value of -128. When I perform an AND with the result and 11111111 I am getting 128. Does this mean that, to convert a signed byte to a unsigned byte we mask it with 0xff? I am trying to understand how it works as it is pretty confusing. Any help is highly appreciated. Thanks!!


Solution

  • When you "upcast" integer primitive types, the sign bit is carried.

    In:

    int x = byte1 ^ byte2;
    

    in fact, both bytes are converted to integers. And since byte2 is (in binary) 1000 0000, aka 0x80, its integer value will be... 0xffffff80.

    In your second example, byte1 ^ byte2 also gives 0xffffff80, but since you and it with 0x000000ff, you do get 0x00000080 which is 128.

    Note that since Java 7 you can do byte b = (byte) 0b1000_0000; in your situation, you may want to use binary instead of hexadecimal, but that's your choice.