java的>>和>>>右移运算符讲解

来源:互联网 发布:ipad有淘宝卖家版吗 编辑:程序博客网 时间:2024/06/05 04:21

可以先到这里了解下计算机的基础知识:原码, 反码, 补码 详解

计算机在运算的过程中采用补码,符号位和补码的出现使计算机可以不用减法计算。


^_^

1. 对于非负数,这两个运算符的作用相同,将原数转换成二进制数后,右移得到结果。

  • 对于0,>>>的实验源码如下:

public class Rtest{public static void main(String[] arg){int a=0;int temp=a;while(true){System.out.println("a="+a);a=a>>>1;if(a==temp){break;}temp=a;}}}
实验结果如下:




  • 对于0,>>的实验源码如下:

public class Rtest{public static void main(String[] arg){int a=0;int temp=a;while(true){System.out.println("a="+a);a=a>>1;if(a==temp){break;}temp=a;}}}
以上实验结果:


  • 对于正整数1000,>>>的实验源码如下:

public class Rtest{public static void main(String[] arg){int a=1000;int temp=a;while(true){System.out.println("a="+a);a=a>>>1;if(a==temp){break;}temp=a;}}}
实验结果如下:


  • 对于正整数1000,>>的实验源码如下:

public class Rtest{public static void main(String[] arg){int a=1000;int temp=a;while(true){System.out.println("a="+a);a=a>>1;if(a==temp){break;}temp=a;}}}
实验结果如下:



2. 对于负数,>>不将符号位参与运算,不断右移后的最终结果为-1。>>>将符号位参与运算。

  • 对于负数-1000,>>的的实验源码如下:

public class Rtest{public static void main(String[] arg){int a=-1000;int temp=a;while(true){System.out.println("a="+a);a=a>>1;if(a==temp){break;}temp=a;}}}
实验结果如下:


  • 对于负数-1000,>>>的的实验源码如下:

public class Rtest{public static void main(String[] arg){int a=-1000;int temp=a;while(true){System.out.println("a="+a);a=a>>>1;if(a==temp){break;}temp=a;}}}
实验结果如下:

-1000

原码:1000 0000 0000 0000 0000 0011 1110 1000

补码:1111 1111  1111  1111  1111  1100  0001 1000

对补码>>>运算后:0111 1111  1111  1111  1111  1110  0000 1100

好了,先记下这么多了~

阅读全文
0 0
原创粉丝点击