这段代码为什么没有按照我想的方式输出?(关于位移)

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

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-2.html
匿名

发表评论

匿名网友

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

确定