I am trying to make a program to calculate 1's complement after entering a binary number. This is what I have to far:
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.
Any help?
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.