Java中的二进制运算

Integer a = 127;
Integer b = 127;
System.out.println(a == b);
Integer c = 128;
Integer d = 128;
System.out.println(c == d);

/*
输出:
true
false
*/


/*
原因:
如果两个引用指向相同的对象,它们在 == 表达式中是相等的;
如果两个引用指向不同的对象,尽管它们拥有相同的内容即值,在 == 表达式中也是不相等的。
127相等的原因:
从源码中可知:Integer类的内部设置了缓存,为-128到127之间,所以只要在这个区间之间,就是同一对象,并没有创建新的对象
*/
Integer//32位
public static final int   MIN_VALUE = 0x80000000;
//1000_0000_0000_0000_0000_0000_0000_0000 //作为负数最大值
//0000_0000_0000_0000_0000_0000_0000_0000 //作为0  
//二进制数在内存中是以补码的形式存放的,正数的补码,反码都是其本身
/*
源码:1000_0000_0000_0000_0000_0000_0000_0000   //最高位存放符号, 正数为0, 负数为1
反码:1111_1111_1111_1111_1111_1111_1111_1111   //符号位不变,在原码的基础上其余位取反
补码:1000 0000 0000 0000 0000 0000 0000 0000   // 符号位不变,在反码的基础上+1
*/
/*
补码-->原码:再求一次补码

*/
//二进制赋值,这是Java7中引入的特性,在编译时会去掉下划线。
int a = 0b1_1011;
System.out.println(a);
//输出27
int a = -4;//原码:1000 0000 0000 0000 0000 0000 0000 0100
System.out.println(Integer.toBinaryString(a));
//1111 1111 1111 1111 1111 1111 1111 1100 //用的补码

int b = 0b1000_0000_0000_0000_0000_0000_0000_0100;
System.out.println(b);//-2147483644
//说明赋值的时候也要用补码赋值
/*又原码得到补码*/

int b = 0b1000_0000_0000_0000_0000_0000_0000_0100;
//求b的补码

//除符号位取反,得到反码
b = b<<1;
b = ~b;
b = b>>1;
//在反码的基础上+1,得到补码
b = b+1;
System.out.println(Integer.toBinaryString(b));
//输出:11111111111111111111111111111100
System.out.println(b);
//输出:-4
//负数最大值
int a = 0b1111_1111_1111_1111_1111_1111_1111_1111;//负数最小值的原码
int b = 0b1000_0000_0000_0000_0000_0000_0000_0001;//b是a的补码
System.out.println(Integer.MIN_VALUE);
System.out.println(b);
/*
输出:
-2147483648
-2147483647
*/
/*
可以看出最小值是多1的
实际上负数最小值为public static final int   MIN_VALUE = 0x80000000
即:1000_0000_0000_0000_0000_0000_0000_0000
*/
//例子
int b = 0x80000000;
//1000_0000_0000_0000_0000_0000_0000_0000 //补码是本身
//1111_1111_1111_1111_1111_1111_1111_1111
//1000_0000_0000_0000_0000_0000_0000_0000
System.out.println(b);
System.out.println(Integer.MIN_VALUE);
int c = 0b1000_0000_0000_0000_0000_0000_0000_0000;
System.out.println(c);
/*
输出:
-2147483648
-2147483648
-2147483648
*/
//java取反
int c = 1;
c = ~c;//所有位都取反,不区分符号位,数值位
System.out.println(Integer.toBinaryString(c));
//输出:11111111111111111111111111111110



//进制赋值
int a = 0x10000004;//原码值为:-4
System.out.println(a);//输出:268435460
//可以看出赋值都是按照补码赋值的
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值