Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding 1's complement

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?

like image 506
user2913004 Avatar asked Oct 26 '13 17:10

user2913004


People also ask

How do you find 1s and 2s complement?

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.

How is 1's complement of a binary number obtained?

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).

Why do we find 1s complement?

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.

What is the 1s complement of 33?

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.


2 Answers

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.

like image 153
arshajii Avatar answered Nov 13 '22 08:11

arshajii


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.

like image 39
CmdrMoozy Avatar answered Nov 13 '22 07:11

CmdrMoozy