Can't byte variable express 125 in Java?

190 views Asked by At

I'm totally java beginner and not good at English. So I don't know how to ask what I really want to know, but I trying..

After I learned some code about using byte I practiced. But the result was not what I expected.. below is my code!

public static void main(String[] args){
    byte n1 = -2; // 10000010
    byte r1 = (byte) (~n1); // expectation: 125(01111101)
    System.out.println(r1);
}

but the result was "1"..

I learned that byte can express -128~+127 and I thought Eclipse would show me "125", but it was "1" so I want to know why..

Thank you for your attention to my question.

1

There are 1 answers

1
Antimony On BEST ANSWER

~x is equivalent to x ^ -1 in Java, so ~n1 is -2 ^ -1 = 1.

As Eran pointed out in the comments, the issue is that you are mistaken about the bitwise representation of -2. -2 is 11111110, while 1000010 is actually -126.