为什么这段代码的输出结果与我想的不一样?(关于移位操作)

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

Why doesn't this code output the way I think? (about shift)

问题

public static void maain(String[] args){
    int a = -11;
    System.out.println(" a= "+a+"("+Integer.toBinaryString(a)+")");
    System.out.println(" a>>2= "+(a>>2)+"("+Integer.toBinaryString(a>>2)+")");
    System.out.println(" a>>>2= "+(a>>>2)+"("+Integer.toBinaryString(a>>>2)+")");
}

我认为 a>>>2 的输出应该是 001111111111111111111111111101,因为 >>> 表示右移并用 0 填充空白位。我想得对吗?

英文:
public static void maain(String[] args){
    int a = -11;
    System.out.println(" a= "+a+"("+Integer.toBinaryString(a)+")");
    System.out.println(" a>>2= "+(a>>2)+"("+Integer.toBinaryString(a>>2)+")");
    System.out.println(" a>>>2= "+(a>>>2)+"("+Integer.toBinaryString(a>>>2)+")");
}

I think a>>>2 output is 001111111111111111111111111101, because >>> means shift right and fill blanks with 0. Am I thinking wrong?

答案1

得分: 1

为什么你认为Integer.toBinaryString()会输出前导零?文档明确说明了不会输出前导零:

> 如果无符号的数值为零,则表示为单个零字符'0' ('\u0030');否则,无符号数值的表示中的第一个字符不会是零字符。

Java没有提供内置方法将整数转换为带有前导零的二进制表示。在https://stackoverflow.com/questions/4421400/how-to-get-0-padded-binary-representation-of-an-integer-in-java 上提供了几种可能的解决方案。

例如,你可以使用以下代码:

System.out.println(" a>>>2= "+(a>>>2)+"("+String.format("%32s", Integer.toBinaryString(a>>>2)).replace(' ', '0')+")");
英文:

Why do you think that Integer.toBinaryString() outputs leading zeros? The documentation clearly states otherwise:

> If the unsigned magnitude is zero, it is represented by a single zero character '0' ('\u0030'); otherwise, the first character of the representation of the unsigned magnitude will not be the zero character.

Java doesn't offer a built-in method to convert an integer into a binary representation with leading zeros. Several possible solutions are offered at https://stackoverflow.com/questions/4421400/how-to-get-0-padded-binary-representation-of-an-integer-in-java

For example you could use:

System.out.println(" a>>>2= "+(a>>>2)+"("+String.format("%32s", Integer.toBinaryString(a>>>2)).replace(' ', '0')+")");

huangapple
  • 本文由 发表于 2023年8月9日 14:19:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76865059.html
匿名

发表评论

匿名网友

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

确定