位运算

左移(<<)

尖括号指向左边(<<),a<<b表示a向左移动b位,即a = a * 2^b

a向左移动b位: 先将a转为2进制,然后将a转为的二进制整体向左移动b位,低位用0补齐

左移位例子

System.out.println("移位前" + Integer.toBinaryString(10));
System.out.println("左移位后" + Integer.toBinaryString(10 << 2));
/*

移位前: 00000000 00000000 00000000 00001010
移位后: 00000000 00000000 00000000 00101000
*/

右移(>>)

尖括号指向右边(>>),a>>b表示a向右移动b位,即a = a / 2^b

a向左移动b位: 先将a转为2进制,然后将a转为的二进制整体向右移动b位,非负整数高位用0补齐,负整数用1补齐

右移位例子

System.out.println("移位前" + Integer.toBinaryString(10));
System.out.println("右移位后" + Integer.toBinaryString(10 >> 2));
/*
移位前: 00000000 00000000 00000000  00001010
移位后: 00000000 00000000 00000000  00000010
*/

位与(&)

将两个数转换为2进制,相应位置上两者都为1才为1,否则为0

System.out.println("运算前" + Integer.toBinaryString(5) + "  " + Integer.toBinaryString(3));
System.out.println("位运算" + Integer.toBinaryString(5 & 3));
/*
运算前:
    5: 00000000 00000000 00000000  00000101
    3: 00000000 00000000 00000000  00000011
运算后: 00000000 00000000 00000000  00000001
*/

位或(|)

将两个数转换为2进制,相应位置上两者都为0才为0,否则为1

System.out.println("运算前" + Integer.toBinaryString(5) + "  " + Integer.toBinaryString(3));
System.out.println("位运算" + Integer.toBinaryString(5 | 3));
/*
运算前:
    5: 00000000 00000000 00000000  00000101
    3: 00000000 00000000 00000000  00000011
运算后: 00000000 00000000 00000000  00000111
*/

位异或(^)

将两个数转换为2进制,相应位置上两者不同为1,否则为0

System.out.println("运算前" + Integer.toBinaryString(5) + "  " + Integer.toBinaryString(3));
System.out.println("位运算" + Integer.toBinaryString(5 ^ 3));
/*
运算前:
    5: 00000000 00000000 00000000  00000101
    3: 00000000 00000000 00000000  00000011
运算后: 00000000 00000000 00000000  00000110
*/

位非(~)

将数字转为2进制,把所有的0变为1,把0变为1

System.out.println("位运算" + Integer.toBinaryString(~5));
/*
运算前:
    5: 00000000 00000000 00000000  00000101
运算后: 11111111 11111111 11111111  11111010
*/
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值