移位运算符<<、>>、>>>在Java中的用法

来源:互联网 发布:js函数传递对象参数 编辑:程序博客网 时间:2024/06/06 12:55

<<:

左移: 8 <<= 1 相当于8 * 2^1、8 <<= 2 相当于8 * 2^2

>>:

右移:8 >>= 1 相当于8 / 2^1、8 >>= 2 相当于8 / 2^2

>>>:

无符号右移:无符号右移,忽略符号位,空位都以0补齐

正数>>>:与右移一样        负数>>>:如下

用代码展示会更直观一些:

public class Test {    public static void main(String[] args){    int x = -8;    System.out.println("x = "+x);    x <<= 1;//x * 2^1    System.out.println("x << 1 = "+x);    x >>= 1;//x / 2^1    System.out.println("x >> 2 = "+x);    System.out.println("8的2进制:"+Integer.toBinaryString(8));    //负数的2进制是正数的2进制取反加一    System.out.println("-8的2进制:"+Integer.toBinaryString(-8));    int cha = Math.abs(x) / 2;//绝对值/2,用于求>>>值,    x >>>= 1;//无符号右移,忽略符号位,空位都以0补齐    System.out.println("x >>> 1 = "+x);    System.out.println("x的2进制:"+Integer.toBinaryString(x));    double y = Math.pow(2, 32)-Math.pow(2, 32-1)-cha;//自己找的规律,不知道是不是最简便的    if(x == y){    System.out.println("true");    }    }}


以上就是移位运算符的用法,例子用的是负数,正数与之类似。

原创粉丝点击