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. 测试代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
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中的移动位运算:,>>>详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!
原文链接:https://blog.csdn.net/weixin_34414196/article/details/87551511