简体   繁体   中英

Automatic Type Promotion in Java

I understand that the operands are automatically converted to int and we need to cast the expression to byte again. And for byte conversion the 24 bits are truncated and only 8 bits are evaluated. But I am not able to understand this output -56. The final value of e is 200 and converting it in binary gives 11001000. How is the output -56?

 public class ByteIntAutomaticPromotionInExpressions {
        public static void main(String[] args) {
            byte e = 50;
            e = (byte)(e *2);
            System.out.println(e);
            e *= 2;
            System.out.println(e);


    }
}

OUTPUT:

100
-56

As you can see here:

byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive).

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

If the data type was unsigned, 11001000 would be 200 in decimal. But since it is signed, you treat it like a negative binary number which is -(inverted bits +1) => - (0110111 + 1) = -(0111000) = -56

https://www.allaboutcircuits.com/textbook/digital/chpt-2/negative-binary-numbers/

8位,在这种情况下2 ^ 8 = 256 200-256 = -56

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM