3

This is my code:

public class test {

  public static void main(String[] args) {
    byte a=(byte)127, b=2;    
    byte c=(byte)(a*b);

    System.out.println(c);
  }    
}

Why is the result -2?

Maroun
  • 94,125
  • 30
  • 188
  • 241

6 Answers6

9

Because a*b will result in a temporary int variable, namely, 254, which is 1111 1110. When cast to byte, this will be handled as a signed value. The MSB is 1, so its value will be negative, and the value will be -(((inv)111 1110) + 1) = -((000 0001) + 1) = -2.

András Hummer
  • 960
  • 1
  • 17
  • 35
3

a * b is 254, so your code is:

byte c=(byte)254;

The decimal 254 is the binary 11111110, which is: -2. Why?

First of all, the number is negative since it begins with 1 (Two's complement), then:

¬ 1 1 1 1 1 1 1 0 is 0 0 0 0 0 0 0 1.

0 0 0 0 0 0 0 1
              1 +
---------------
0 0 0 0 0 0 1 0 

This represents 2 in decimal, but remember that the MSB is 1? So final result is -2.

Maroun
  • 94,125
  • 30
  • 188
  • 241
0

Since byte is a signed type 2 * 127 is binary "11111110", which is two's complement for -2.

Mithrandir
  • 24,869
  • 6
  • 50
  • 66
0

because byte is signed, not unsigned.

254 = FE = 1111 1110

the first '1' represent the number as a negative number.

RamonBoza
  • 8,898
  • 6
  • 36
  • 48
0

127 in 8 bits is represented in binary like this:

01111111

Multiply by 2, and you get this:

11111110

(When you multiply by 10 in base 10, all the digits can be shifted left, to the next position. The same is naturally true when you multiply by 2 in binary)

Java uses 2's complement to represent negative numbers. Basically, the left-most bit is the sign bit (0 for +, 1 for -). To convert a positive number in a negative number, flip all the bits and add one.

Example: 00000010 = 2, flip the bits: 11111101, then add one: 11111110 = -2. This is the same as 127*2 above.

NickJ
  • 9,380
  • 9
  • 51
  • 74
0

I think what you tried to ask is why overflow of a 8bits signed integer will turned to negative number for your case.
As in CPU, there is not a 8bits ALU, so 8bits will be expand to 32bits, after operation, return the lower 8bits to user.
In CPU: 0000_007F * 0000_0002 = 0000_00FE
This is a overflow for signed 8bits, but the value has been calculated already.
So returned value is FE.
For 8bits signed, FE is -2.

TerrenceSun
  • 433
  • 3
  • 15