|
| 1 | +--- |
| 2 | +title: Java Program to Add two Binary Numbers |
| 3 | +shortTitle: Add two Binary Numbers |
| 4 | +description: In this tutorial we will write a java program to add two binary numbers. |
| 5 | +--- |
| 6 | + |
| 7 | +Binary number system has only two symbols **0** & **1** so a **binary numbers** consists of only 0’s and 1’s. Before we write a program for addition, lets see how we do the addition on paper, this is shown in the diagram below: |
| 8 | + |
| 9 | + |
| 10 | +## Adding binary numbers in Java |
| 11 | + |
| 12 | +### Code: |
| 13 | + |
| 14 | +```java |
| 15 | +import java.util.Scanner; |
| 16 | +public class JavaExample { |
| 17 | + public static void main(String[] args) |
| 18 | + { |
| 19 | + //Two variables to hold two input binary numbers |
| 20 | + long b1, b2; |
| 21 | + int i = 0, carry = 0; |
| 22 | + |
| 23 | + //This is to hold the output binary number |
| 24 | + int[] sum = new int[10]; |
| 25 | + |
| 26 | + //To read the input binary numbers entered by user |
| 27 | + Scanner scanner = new Scanner(System.in); |
| 28 | + |
| 29 | + //getting first binary number from user |
| 30 | + System.out.print("Enter first binary number: "); |
| 31 | + b1 = scanner.nextLong(); |
| 32 | + //getting second binary number from user |
| 33 | + System.out.print("Enter second binary number: "); |
| 34 | + b2 = scanner.nextLong(); |
| 35 | + |
| 36 | + //closing scanner after use to avoid memory leak |
| 37 | + scanner.close(); |
| 38 | + while (b1 != 0 || b2 != 0) |
| 39 | + { |
| 40 | + sum[i++] = (int)((b1 % 10 + b2 % 10 + carry) % 2); |
| 41 | + carry = (int)((b1 % 10 + b2 % 10 + carry) / 2); |
| 42 | + b1 = b1 / 10; |
| 43 | + b2 = b2 / 10; |
| 44 | + } |
| 45 | + if (carry != 0) { |
| 46 | + sum[i++] = carry; |
| 47 | + } |
| 48 | + --i; |
| 49 | + System.out.print("Output: "); |
| 50 | + while (i >= 0) { |
| 51 | + System.out.print(sum[i--]); |
| 52 | + } |
| 53 | + System.out.print("\n"); |
| 54 | + } |
| 55 | +} |
| 56 | +``` |
| 57 | +### Output: |
| 58 | + |
| 59 | +```text |
| 60 | +Enter first binary number: 11100 |
| 61 | +Enter second binary number: 10101 |
| 62 | +Output: 110001 |
| 63 | +``` |
0 commit comments