欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

浅谈java中的移动位运算:,>>>

程序员文章站 2024-02-27 19:04:09
1. 概念 << 左移运算符,左移是在后面补0, num << 1,相当于num乘以2 >> 右移运算符, 右移是在前面补1或0,n...

1. 概念

<< 左移运算符,左移是在后面补0, num << 1,相当于num乘以2
>> 右移运算符, 右移是在前面补1或0,num >> 1, 相当于num除以2
>>> 无符号右移,是在前面补0, 忽略符号位,空位都以0补齐
另外, 不论是左右还是右移32位,相当于不移动,还是原值。

实际上 在java虚拟机执行这句代码的时候如下这样执行的:
5>>(n%32)--->结果
你这里n=32 ;所以5>>32即是 5>>(32%32)-->5>>0 的结果;

2. 测试代码

public class test{
 public test(){
 system.out.println("=============算术右移 >> ===========");
 int i=0xc0000000;
 system.out.println("移位前:i= "+i+" = "+integer.tobinarystring(i)+"(b)");
 i=i>>28;
 system.out.println("移位后:i= "+i+" = "+integer.tobinarystring(i)+"(b)");
 
 system.out.println("---------------------------------");
 
 int j=0x0c000000;
 system.out.println("移位前:j= "+j+" = "+integer.tobinarystring(j)+"(b)");
 j=j>>24;
 system.out.println("移位后:j= "+j+" = "+integer.tobinarystring(j)+"(b)");
 
 system.out.println("\n");
 system.out.println("==============逻辑右移 >>> =============");
 int m=0xc0000000;
 system.out.println("移位前:m= "+m+" = "+integer.tobinarystring(m)+"(b)");
 m=m >>> 28;
 system.out.println("移位后:m= "+m+" = "+integer.tobinarystring(m)+"(b)");
 
 system.out.println("---------------------------------");
 
 int n=0x0c000000;
 system.out.println("移位前:n= "+n+" = "+integer.tobinarystring(n)+"(b)");
 n=n>>24;
 system.out.println("移位后:n= "+n+" = "+integer.tobinarystring(n)+"(b)");
 
 system.out.println("\n");
 system.out.println("==============移位符号的取模===============");
 int a=0xcc000000;
 system.out.println("移位前:a= "+a+" = "+integer.tobinarystring(a)+"(b)");
 system.out.println("算术右移32:a="+(a>>32)+" = "+integer.tobinarystring(a>>32)+"(b)");
 system.out.println("逻辑右移32:a="+(a>>>32)+" = "+integer.tobinarystring(a>>>32)+"(b)");
 
 system.out.println("算术右移64:a="+(a>>64)+" = "+integer.tobinarystring(a>>64)+"(b)");
 system.out.println("逻辑右移64:a="+(a>>>64)+" = "+integer.tobinarystring(a>>>64)+"(b)");
 
 }
 
 public static void main(string[] args){
 new test();
 }
 
}
 

运行结果:

=============算术右移 >> ===========
移位前:i= -1073741824 = 11000000000000000000000000000000(b)
移位后:i= -4 = 11111111111111111111111111111100(b)

移位前:j= 201326592 = 1100000000000000000000000000(b)
移位后:j= 12 = 1100(b)

==============逻辑右移 >>> =============
移位前:m= -1073741824 = 11000000000000000000000000000000(b)
移位后:m= 12 = 1100(b)

移位前:n= 201326592 = 1100000000000000000000000000(b)
移位后:n= 12 = 1100(b)

==============移位符号的取模===============
移位前:a= -872415232 = 11001100000000000000000000000000(b)
算术右移32:a=-872415232 = 11001100000000000000000000000000(b)
逻辑右移32:a=-872415232 = 11001100000000000000000000000000(b)
算术右移64:a=-872415232 = 11001100000000000000000000000000(b)
逻辑右移64:a=-872415232 = 11001100000000000000000000000000(b)

3. 为什么没有无符号左移

这个问题大家可以思考一下,应该能想出来。(提示:没有就是没有存在的意思)

以上所述是小编给大家介绍的java中的移动位运算:,>>>详解整合,希望对大家有所帮助