Reputation: 31
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
?
Upvotes: 3
Views: 644
Reputation: 473
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
.
Upvotes: 0
Reputation: 9579
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.
Upvotes: 0
Reputation: 95998
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.
Upvotes: 3
Reputation: 972
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.
Upvotes: 9
Reputation: 9038
because byte is signed, not unsigned.
254 = FE = 1111 1110
the first '1'
represent the number as a negative number.
Upvotes: 0
Reputation: 25387
Since byte is a signed type 2 * 127 is binary "11111110", which is two's complement for -2.
Upvotes: 0