java 位移运算 >>

2025-10-26 00:35:00

1、左侧位移 :<<   表示这个数乘以2的n次方

右侧位移:>>    表示除以这个数的n次方

2、示例:

y<<1 等价于 y*(Math.pow(2, 1))

y<<2 等价于 y*(Math.pow(2, 2))

y<<3   等价于 y*(Math.pow(2, 3)) 

y<<4   等价于 y*(Math.pow(2, 4))

y<<5   等价于 y*(Math.pow(2, 5))

y>>1 等价于 y/(Math.pow(2, 1))

y>>2 等价于 y/(Math.pow(2, 2))

y>>3 等价于 y/(Math.pow(2, 3)) 

y>>4 等价于 y/(Math.pow(2, 4))

y>>5 等价于 y/(Math.pow(2, 5))

3、// java 代码  运算结果有些出入哦。。。。

int y=10;

System.out.println(( y<<1 )+"  <<   "+(y*(Math.pow(2, 1))));

System.out.println(( y<<2 )+"  <<   "+(y*(Math.pow(2, 2))));

System.out.println(( y<<3 )+"  <<   "+(y*(Math.pow(2, 3))));

System.out.println(( y<<4 )+"  <<   "+(y*(Math.pow(2, 4))));

System.out.println(( y<<5 )+"  <<   "+(y*(Math.pow(2, 5))));

System.out.println("------ 分割线 ------"); 

y=1000;// (如下 >> 示例 : y 的值不能写太小 ,否则强制类型转换了) 

System.out.println(( y>>1 )+"  >>   "+(y/(Math.pow(2, 1))));

System.out.println(( y>>2 )+"  >>   "+(y/(Math.pow(2, 2))));

System.out.println(( y>>3 )+"  >>   "+(y/(Math.pow(2, 3))));

System.out.println(( y>>4 )+"  >>   "+(y/(Math.pow(2, 4))));

System.out.println(( y>>5 )+"  >>   "+(y/(Math.pow(2, 5))));

4、运行结果为:

20  <<   20.0

40  <<   40.0

80  <<   80.0

160  <<   160.0

320  <<   320.0

------ 分割线 ------

500  >>   500.0

250  >>   250.0

125  >>   125.0

62  >>   62.5

31  >>   31.25

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢