# 这段代码为什么没有按照我想的方式输出？（关于位移）

go评论105阅读模式

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)+")");
}
``````

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

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

# 答案1

> 如果无符号幅度为零，则由单个零字符 '0'（'\u0030'）表示；否则，无符号幅度的表示的第一个字符将不是零字符。

``````System.out.println(" a&gt;&gt;&gt;2= "+(a&gt;&gt;&gt;2)+"("+String.format("%32s", Integer.toBinaryString(a&gt;&gt;&gt;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(&quot; a&gt;&gt;&gt;2= &quot;+(a&gt;&gt;&gt;2)+&quot;(&quot;+String.format(&quot;%32s&quot;, Integer.toBinaryString(a&gt;&gt;&gt;2)).replace(&#39; &#39;, &#39;0&#39;)+&quot;)&quot;);
``````

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

go 50

go 53

go 50

go 51