英文:
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')+")");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论