Java – when we change to bytes, why is the result – 2 when 127 * 2?
•
Java
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?
Solution
Because a * B will result in a temporary int variable, i.e. 254, i.e. 1111 1110 When converted to byte, this is treated as a signed value MSB is 1, so its value is negative, and the value is – ((INV) 111 1110) 1) = – ((000 0001) 1) = - 2
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码