-6

Can someone please let me know Output of the below program and how signed byte works

public class OppositeSigns 
{
    public static void main(String[] args) 
    {
      // TODO Auto-generated method stub

      byte a =-2;
      byte b= -1;
      opp(a,b);
    }

    static void opp(byte x,byte y)
    {
      byte z;
      z= (byte)(x^y);
      System.out.println(z);
    }
}
Prerak Sola
  • 9,517
  • 7
  • 36
  • 67

1 Answers1

1
-1 is 11111111 in binary
-2 is 11111110 in binary

when you XOR the two numbers, you get

      00000001

which is 1

Eran
  • 387,369
  • 54
  • 702
  • 768
  • 3
    Except you're not XORing those two bytes. You're XORing the 32-bit integers. The answer ends up being the same, but it's worth knowing that integer promotion happens first. – Jon Skeet Dec 29 '14 at 08:48
  • Thanks a lot@eran. But how signed byte is represented is -1= 10000001? – Rahul Lamba Dec 29 '14 at 08:55
  • @RahulLamba Read about [Two's complement](http://en.wikipedia.org/wiki/Two%27s_complement) – Eran Dec 29 '14 at 08:56