[英]How to Convert negative decimal to binary number and and use shift operators in Java
我有这个演示程序,它在java中显示了shift运算符的概念。但我不清楚这个程序如何生成这个答案。所以请建议我如何做到这一点。
public class Operator {
public static void main(String[] args) {
int s = -10;
s = s >>2;
System.out.println("value of i=" + s);
}
}
输出:
值i = -3
11110110 2 >> 2 == 11111101 2 == -3 10
这是一个符号扩展的右移操作 - 当它向右移动时,它不会在左边插入零,而是复制最高位的值。 其余的解释是关于有符号整数的两个补码表示。
通常,将负整数右移n
位置将具有除以2 n并从中减去1的效果。
您可以将以下两行添加到程序中以清除一些内容:
System.out.println(Integer.toBinaryString(-10));
System.out.println(Integer.toBinaryString(-3));
//Output:
11111111111111111111111111110110
11111111111111111111111111111101
--^
>> 2
表示将-10
两个位置的二进制重新移位向右移动(产生-3
)。
public void decimalToBinaryUsingBitManipulation(int value)
{
if (value == 0)
return;
decimalToBinaryUsingBitManipulation(value >>> 1);
System.out.print(value & 1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.