# Subtraction of two binary numbers in Java

Hi, today we will learn about **Subtraction of two binary numbers in Java. **This article will help you to develop more knowledge about 2’s complement, binary subtraction as well as binary addition in Java.

First of all, we need to understand that those numbers which are represented through 0’s and 1’s are known as binary numbers. So, subtraction of **B** from **A** can be represented as:

difference = A – B

which can also be written as:

difference = A + (2’s complement of B) = A + (1’s complement of B + 1)

now, the problem is how we obtain 1’s complement of **B. **We will obtain it with the help of ~**, Bitwise Complement Operator: **This is a unary operator that returns the one’s complement representation of the input value. for eg. –

if, **B = 1000010** then the **1’s complement** of B will be: **0111101**

Please Remember there could be multiple ways to solve a particular problem as per your understanding. Before jumping to the code pay attention to the additional rules for the binary numbers:

- 1+1
**=0***(carry=1 will be generated and passed towards left)* - 1+0
**=1** - 0+1
**=1** - 0+0
**=0**

now, let’s have a look at java code.

## Subtraction of two binary numbers: Java Code

import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter A:"); String bin1 = sc.nextLine(); System.out.println("\nEnter B:"); String bin2 = sc.nextLine(); // following method is used to parse the binary number from the string. int A = Integer.parseInt(bin1, 2); int B = Integer.parseInt(bin2, 2); Long sum =(long) A+(~B +1); System.out.println("\ndifference (A - B) is : " + Long.toBinaryString(sum)); /*Long.toBinaryString() method is called to find the binary equivalent in string format*/ sc.close(); } }

output:

Enter A: 11100 //input due to line 10 Enter B: 10101 //input due to line 13 difference (A - B) is : 111

Explanation:

Here, we have-

A=11100 & B=10101, and by using ~**, Bitwise Complement Operator, **we get 1’s complement of B which is: **01010**, now our task is to add **A, 1’s complement of B and 1 **as per the **addition rules** mentioned above**.**

So now you understood how to find the difference between two binary numbers.

you may also read:

Java program to calculate consecutive 1’s in Binary Numbers

## Leave a Reply