public class T1 {
public static void main(String[] args) {
int a=200;
byte b=(byte) a;
System.out.println(b);//输出:-56
}
}
class T2 {
public static void main(String[] args) {
int a=300;
byte b=(byte) a;
System.out.println(b);//输出:44
}
}
1.为什么输出的是-56呢?
解析:首先得明确,计算机实际存储的是补码
int 占四个字节
byte 占一个字节
200的补码为:0000 0000 0000 0000 0000 0000 1100 1000
强转后只能截取到后面一个字节
因此强转后b的补码为:1100 1000(知道了为什么是负数)
b的反码为:1100 0111(补码-1)
b的源码为:1011 1000 (反码)
通过进制转换可知为-56;
2.为什么是44呢?
同理
300的补码:0000 0000 0000 0000 0000 0001 0010 1100
截取:0010 1100
源码:0010 1100
(正数的反码,补码,源码都一样)(三码合一)
进制转换为:44