Scanner class Methods in Java

2)1's and 2's Complement in Binary to store negative numbers

In the previous post we discussed about binary language,. Now ,We will learn 1's complement and 2's complement in binary to store negative numbers.

1's Complement

I's complement is just the inverse of binary numbers.We just toggle 1 with 0 and 0 with one.
For example: 1100 is a binary number and 0011 is its 1's complement.Just replace the 0's with 1's and vice versa.

Representing negative number with 1's Complement

Sign bit is used to represent positive or negative sign of number.If the Sign Bit is 0 ,number is positive and if it is 1 the number is negative.

For example: We want to store -3 ,follow the steps: 
  1.  3 in binary is 0111, but we will use its actual value that is 111.          
  2.  The 1's complement of 111 is 000.
  3.  To make 3 negative we will use 1 as sign bit
So, the -3 is stored as 1000 with 1's complement

2's Complement

To obtain 2's complement, we just add 1 to the 1's complement of the binary number.First you obtain the 1's complement of a binary number then add 1 to it.

For example:We have a binary number 1100, to convert it to 2's complement follow the steps as below,

  1.  Write binary number,            1100
  2. Find its 1's complement,        0011
  3.  Add 1 to the 1's complement    +1 
  4. After Addition,Result is         0100
In Binary, 1+1= 10 and we write 0 and 1 becomes carry which is added to next digit like math.And 0+1=1 & 0+0=0 in binary addition.If you have any doubt you can ask in comment section.

Representing negative number with 2's Complement

Sign bit is used to represent positive or negative sign of number.If the Sign Bit is 0 ,number is positive and if it is 1 the number is negative.

For example: We want to store -3 ,follow the steps:
  1. 3 in binary is 0111, but we will use its actual value that is 111.
  2. The 1's complement of 111 is 000.
  3.  Add 1 to 1's complement of number,
  4. The 2's complement is 001                              

So, the -3 is stored as 1001 with 2's complement.
To work with negative numbers and bitwise operators it is important for you to learn these formats.
Keep learning!  Happy Coding!

Comments