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