Java 寻找 1 的补码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19609566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 18:45:19  来源:igfitidea点击:

Finding 1's complement

javaones-complement

提问by user2913004

I am trying to make a program to calculate 1's complement after entering a binary number. This is what I have to far:

我正在尝试编写一个程序来在输入二进制数后计算 1 的补码。这是我必须做的:

import java.util.Scanner;
public class BitWiseComplement {
    public static void main(String[] args) {
        Scanner keysIn = new Scanner(System.in);
        System.out.println("Please enter your number: ");
        long originalNum = keysIn.nextLong();
        System.out.println(~originalNum);
  }
}

However, when I enter 0111011, I get -111012. I thought the ~ operator was supposed to invert the number so that all 0s are 1s and all 1s are 0s.

但是,当我输入 0111011 时,我得到 -111012。我认为 ~ 运算符应该反转数字,以便所有 0 都是 1,所有 1 都是 0。

Any help?

有什么帮助吗?

采纳答案by arshajii

You presumably want to work in binary, so try:

你大概想在二进制中工作,所以尝试:

Scanner keysIn = new Scanner(System.in);
System.out.print("Please enter your number: ");

long originalNum = keysIn.nextLong(2);  // specify radix of 2
System.out.println(Long.toBinaryString(~originalNum));  // print binary string

keysIn.close();
Please enter your number: 0111011
1111111111111111111111111111111111111111111111111111111111000100

As you can see, all bits are flipped. Bear in mind that there are leading 0s in front of the binary number you entered.

如您所见,所有位都被翻转。请记住,您输入的二进制数前面有前导 0。

回答by CmdrMoozy

The ~operator does what you think, but keep in mind that there are no unsigned types in Java, so when you enter a positive number (i.e., the high bit is a 0), applying ~to it will make it negative (by turning the high bit on).

~运营商做什么,你想,但要记住,有没有无符号类型在Java中,所以当你输入一个正数(即高位为0),应用~到它将使负(通过关闭高有点)。

If you were to print the number out in hex (or binary, as other answers have suggested), you should see the answer you expect.

如果您要以十六进制(或二进制,正如其他答案所建议的那样)打印出数字,您应该会看到您期望的答案。