byte为什么要&0xff
原码反码补码这三个概念
对于正数(00000001)原码来说,首位表示符号位,反码 补码都是本身
对于负数(100000001)原码来说,反码是对原码除了符号位之外作取反运算即(111111110),补码是对反码作+1运算即(111111111)
byte占8位,int占32位
也就是说在byte向int扩展的时候,自动转型是按符号位扩展的,这样子能保证十进制的数值不会变化,
而&0xff是补0扩展的,这样子能保证二进制存储的一致性,但是十进制数值已经发生变化了。
也就是说按符号位扩展能保证十进制数值不变,补0扩展能保证二进制存储不会变。
而正数可以说是既按符号位扩展,又是补0扩展,所以在二进制存储和十进制数值上都能保证一致。
做个实验:
public static void main(String[] args) {
// TODO Auto-generated method stub
int i =129;
System.out.print("toBinaryString i="+Integer.toBinaryString(i)+"\n");
System.out.print("toHexString i="+Integer.toHexString(i)+"\n");
System.out.print("toString i="+Integer.toString(i)+"\n");
byte b1 = (byte)i;
System.out.print("toBinaryString b1="+Integer.toBinaryString(b1)+"\n");
System.out.print("toHexString b1="+Integer.toHexString(b1)+"\n");
System.out.print("toString b1="+Integer.toString(b1)+"\n");
byte b2 = (byte)(129&0xFF);
System.out.print("toBinaryString b2="+Integer.toBinaryString(b2)+"\n");
System.out.print("toHexString b2="+Integer.toHexString(b2)+"\n");
System.out.print("toString b2="+Integer.toString(b2)+"\n");
int j = b2;
System.out.print("toBinaryString j="+Integer.toBinaryString(j)+"\n");
System.out.print("toHexString j="+Integer.toHexString(j)+"\n");
System.out.print("toString j="+Integer.toString(j)+"\n");
int j2 = b2&0xFF;
System.out.print("toBinaryString j2="+Integer.toBinaryString(j2)+"\n");
System.out.print("toHexString j2="+Integer.toHexString(j2)+"\n");
System.out.print("toString j2="+Integer.toString(j2)+"\n");
int k1 = b2<<2;
System.out.print("toBinaryString k1="+Integer.toBinaryString(k1)+"\n");
System.out.print("toHexString k1="+Integer.toHexString(k1)+"\n");
System.out.print("toString k1="+Integer.toString(k1)+"\n");
int k2 = (b2&0xFF)<<2;
System.out.print("toBinaryString k2="+Integer.toBinaryString(k2)+"\n");
System.out.print("toHexString k2="+Integer.toHexString(k2)+"\n");
System.out.print("toString k2="+Integer.toString(k2)+"\n");
}
输出结果:
toBinaryString i=10000001
toHexString i=81
toString i=129
toBinaryString b1=11111111111111111111111110000001
toHexString b1=ffffff81
toString b1=-127
toBinaryString b2=11111111111111111111111110000001
toHexString b2=ffffff81
toString b2=-127
toBinaryString j=11111111111111111111111110000001
toHexString j=ffffff81
toString j=-127
toBinaryString j2=10000001
toHexString j2=81
toString j2=129
toBinaryString k1=11111111111111111111111000000100
toHexString k1=fffffe04
toString k1=-508
toBinaryString k2=1000000100
toHexString k2=204
toString k2=516
[0x7FFBAB46E0A4] ANOMALY: use of REX.w is meaningless (default operand size is 64)
从上面看出二进制移位、转整数的时候保持二进制一致性就很重要了
参考:
posted on 2021-06-29 11:23 framework开发 阅读(308) 评论(0) 编辑 收藏 举报