Java:右移数字1无效

huangapple go评论70阅读模式
英文:

Java: Right shifting the number 1 does not work

问题

我正在尝试将数字1向右移动。

因此最初,位掩码应为:

1

然后,位掩码应为:

01

以下是我的代码:

int bitmask = 1;
bitmask >>= 1;
System.out.println(Integer.toBinaryString(bitmask));

然而,输出结果只是:

0
英文:

I am trying to shift the number 1 to the right.

So originally, the bit mask should be:

1

Then, the bit mask should be:

01

Below is my code:

int bitmask = 1;
bitmask >>= 1;
System.out.println(Integer.toBinaryString(bitmask));

The output however, is just:

0

答案1

得分: 2

也许我们对位运算的工作原理有所误解。在进行右移操作时,最低有效位(1)会被丢弃。

二进制中的数字 1 是 0b01。这等同于 0b00000001。将其向右移动一位,结果为 0b00。

尝试使用以下代码,查看位运算的效果。

public class MyClass {
    public static void main(String args[]) {
        int bitmask = 0b10;
        System.out.println(Integer.toBinaryString(bitmask));
        bitmask >>= 1;
        System.out.println(Integer.toBinaryString(bitmask));
    }
}

输出结果

10
1
英文:

Maybe we are misunderstanding about how bitshifting works. When doing a right shift, the least significant bit (1) is lost.

1 in binary is 0b01 already. This is equivalent with 0b00000001. Shifting this right results in 0b00.

Try this instead and see that bitshifting works.

public class MyClass {
    public static void main(String args[]) {
        int bitmask = 0b10;
        System.out.println(Integer.toBinaryString(bitmask));
        bitmask >>= 1;
        System.out.println(Integer.toBinaryString(bitmask));
    }
}

Output

10
1

答案2

得分: 1

位掩码 101 或者 001 或者 0...1 都是相同的。当你进行右移操作时,最低位的数字(在你的情况中为1)会被丢弃,因此输出是正确的。

英文:

The bitmask 1 and 01 or 001 or 0...1 are all the same. When you do a right shift the least significant digit (1 in your case) is lost, so the output is correct.

答案3

得分: 0

请尝试以下内容:

public static void main(String[] args) {
    int bitmask = 1;
    bitmask >>= 1;
    int binaryval = Integer.parseInt(Integer.toBinaryString(bitmask));
    String binary = String.format("%2s", Integer.toString(1, 2)).replace(' ', '0');
    System.out.println(binary);
}

关于Integer.toBinaryString(int)的Javadoc说明(部分内容如下):

此值会被转换为二进制(基数为2)的ASCII数字字符串,没有额外的前导0。有关详细信息,请参考此处链接

英文:

Please try the following

public static void main(String[] args) {
	int bitmask = 1;
    bitmask >>= 1;
    int binaryval = Integer.parseInt(Integer.toBinaryString(bitmask));
    String binary = String.format("%2s", Integer.toString(1, 2)).replace(' ', '0');
    System.out.println(binary);
}

The Javadoc for Integer.toBinaryString(int) says (in part),

This value is converted to a string of ASCII digits in binary (base 2) with no extra leading 0s. Reference is made here

huangapple
  • 本文由 发表于 2020年10月23日 08:19:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/64492248.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定