JAVA的移位运算

来源:互联网 发布:php测试工具 编辑:程序博客网 时间:2024/05/01 20:40

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);    }
原创粉丝点击