Java位移操作

    对于Java位移操作,有三种

  1. 左移(<<),规则 : 低位始终补0
  2. 右移(>>),规则:  正数符号位补0,负数符号位补1(符号位为最高位,0-正数,1-负数)
  3. 无符号右移(>>>),规则:符号位(最高位)始终补0

     下面直接上一段代码:

@Test
public void testWeiYi(){

    //右移比较简单
	System.out.println(1L >> 1);
	System.out.println(1L >> 65);
	System.out.println(1L >>> 1);
	System.out.println(1L >>> 65);

	//long型
	System.out.println("long 左移");
	System.out.println(1L << 1);
	System.out.println(1L << 65);

	//int型
	System.out.println("int 左移");
	System.out.println(1 << 1);
	System.out.println(1 << 33);
	System.out.println(1 << 65);

	//short型
	System.out.println("short 左移");
	System.out.println((short)((short)1 << 1));
	System.out.println((short)((short)1 << 17));
	System.out.println((short)((short)1 << 33));
	System.out.println((short)((short)1 << 65));

	//byte型
	System.out.println("byte 左移");
	System.out.println((byte)((byte)1 << 1));
	System.out.println((byte)((byte)1 << 9));
	System.out.println((byte)((byte)1 << 17));
	System.out.println((byte)((byte)1 << 33));
	System.out.println((byte)((byte)1 << 65));

}

运行结果:

 

有没有发现,左移竟然是循环移动的,不过对于byte,short,int都是转成int后,再循环移动

下面总结一下:

  1. 左移(<<),规则 : 低位始终补0, 左移是循环移动
  2. 右移(>>),规则:  正数符号位补0,负数符号位补1(符号位为最高位,0-正数,1-负数)   右移不是循环移动
  3. 无符号右移(>>>),规则:符号位(最高位)始终补0     右移不是循环移动
  4. 对于byte,short,int都是转成int后,再进行位移操作

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值