JAVA的移位运算

java的移位运算

在学习移位运算之前,移位只用于整数,我们首先应该知道计算机对数字是如何存贮的,在计算机中正数使用的原码存贮的,而负数则使用的是补码,补码等于原码取反(符号位不变)+1,
java的移位运算符有三种:<<=左移操作符,低位补0,>>=右移操作符,是正数,则在高位补0,是负数则在高位补1,>>>无符号右移操作符,无论正符都在高位补0,
操作符的用法:操作符左边的值会移动由右边的值指定的位数,在把移动后的值赋给左边的变量。
这里有一个值得注意点的:在thinking in java关于移位中有这么一段话

If you shift a char, byte, or short, it will be promoted to int before the shift takes place, and the result will be an int.2) Only the five low-order bits of the right-hand side will be used.This prevents you from shifting more than the number of bits in an int. If you’re operating on a long, you’ll get a long result. Only the six low-order bits of the right-hand side will be used, so you can’t shift more than the number of bits in a long.

如果对char、byte或者short类型的数值进行移位处理,那么在移位进行之前,它们会被转换为int类型,并且得到的结果也是一个int类型的值。只有数值右端的低5位才有用。这样可防止我们移位超过int型值所具有的位数。(译注:因为2的5次方为32,而int型数值只有32位。)若对一个long类型的数值进行处理,最后得到的记过也是long。此时只会用到数值右端的低6位,以防止移位超过long型数值具有的位数。

有人数值右端的低5位才有用这句话不理解,其实意思是指,如果数值是int类型,移位运算等号右端的值只有低5位才有效,因为int是32为的2的5次方是32,如果等号右边的值超过32就会对32取余。long类型同理。

public static void main(String[] args){
        int i = -1;
        System.out.println(Integer.toBinaryString(i));
        i>>>=10;
        System.out.println(Integer.toBinaryString(i));
        System.out.println(i);
        i = -1;
        System.out.println(Integer.toBinaryString(i));
        i >>>= 33;
        System.out.println(Integer.toBinaryString(i));
        System.out.println(i);
        short j = -1;
        System.out.println(Integer.toBinaryString(j));
        j >>>=10;
        System.out.println(Integer.toBinaryString(j));
        System.out.println(j);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值