Bitshifting在Java中 [英] Bitshifting in Java

查看:160
本文介绍了Bitshifting在Java中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解移位是如何工作的。有人可以解释这一行的含义是:

 ,而((N&安培; 1)== 0)N>> = 1;

其中, N 是一个整数,给我的 N 时,执行的转变。<​​/为例p>

解决方案

将它分解:

N'放大器; 1 会做N之间的二进制比较,而1这是二进制00000000000000000000000000000001。这样,当n在1(正奇数或负偶数)否则结束并且00000000000000000000000000000000它将返回00000000000000000000000000000001

(N&安培; 1)== 0 当n为偶数(或负奇)将因此真假,否则

N'GT;&GT; = 1 等同于 N = N&GT;&GT; 1 。因此,它改变所有的位到右侧,这是由两个(舍去)

大致相当于一个除法

如果如Ñ​​开始作为12随后以二进制这将是1100一个循环后,它将是110(6),相继将是11(3),然后循环将停止。

如果n是0,那么下一个循环后,将仍然是0,并且循环将是无限的。

I'm trying to understand how bit shift works. Can someone please explain the meaning of this line:

while ((n&1)==0) n >>= 1;

where n is an integer and give me an example of a n when the shift is executed.

解决方案

Breaking it down:

n & 1 will do a binary comparison between n, and 1 which is 00000000000000000000000000000001 in binary. As such, it will return 00000000000000000000000000000001 when n ends in a 1 (positive odd or negative even number) and 00000000000000000000000000000000 otherwise.

(n & 1) == 0 will hence be true if n is even (or negative odd) and false otherwise.

n >> = 1 is equivalent to n = n >> 1. As such it shifts all bits to the right, which is roughly equivalent to a division by two (rounding down).

If e.g. n started as 12 then in binary it would be 1100. After one loop it will be 110 (6), after another it will be 11 (3) and then the loop will stop.

If n is 0 then after the next loop it will still be 0, and the loop will be infinite.

这篇关于Bitshifting在Java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆