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?
To get 1's complement of a binary number, simply invert the given number. To get 2's complement of a binary number, simply invert the given number and add 1 to the least significant bit (LSB) of given result.
The ones' complement of a binary number is the value obtained by inverting all the bits in the binary representation of the number (swapping 0s and 1s).
1's complement plays an important role in representing the signed binary numbers. The main use of 1's complement is to represent a signed binary number. Apart from this, it is also used to perform various arithmetic operations such as addition and subtraction.
1's compliment means “Replacing all 1's with 0's & 0's with 1's”. 2's compliment means “Adding 1 to the 1's compliment of the required number”. Ex: 2's compliment of the number – 33 is (1101 1111)2.
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.
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).
If you were to print the number out in hex (or binary, as other answers have suggested), you should see the answer you expect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With