Q:

Java program to find subtraction of two numbers using binary subtraction

belongs to collection: Java Basic Programs

0

Java program to find subtraction of two numbers using binary subtraction

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

In this program, we will read two integer numbers from the user and find the subtraction of input numbers using binary subtraction.

Program/Source Code:

The source code to find subtraction of two numbers using binary subtraction is given below. The given program is compiled and executed successfully.

// Java program to find subtraction of two numbers 
// using binary subtraction

import java.util.Scanner;

public class Main {

  static int binAddition(int a, int b) {
    int c; //carry

    while (b != 0) {
      //find carry and shift it left

      c = (a & b) << 1;

      //find the sum
      a = a ^ b;
      b = c;
    }
    return a;
  }

  static int binSubtracton(int a, int b) {
    int carry;

    //get 2's compliment of b and add in a
    b = binAddition(~b, 1);

    while (b != 0) {
      //find carry and shift it left
      carry = (a & b) << 1;

      a = a ^ b;
      b = carry;
    }
    return a;
  }

  public static void main(String[] args) {
    Scanner SN = new Scanner(System.in);

    int num1 = 0;
    int num2 = 0;
    int add = 0;

    System.out.printf("Input first integer value: ");
    num1 = SN.nextInt();

    System.out.printf("Input second integer value: ");
    num2 = SN.nextInt();

    add = binSubtracton(num1, num2);
    System.out.printf("Binary Subtraction is: %d\n", add);
  }
}

Output:

Input first integer value: 34
Input second integer value: 23
Binary Subtraction is: 11

Explanation:

In the above program, we imported the "java.util.Scanner" package to read input from the user. And, created a public class Main. It contains three static methods binAddition()binSubtraction(), and main().

The binAddition() method is used to add two integer numbers using binary addition and return the result to the calling method.

The binSubtraction() method is used to perform a subtraction between two integer numbers using binary subtraction and return the result to the calling method.

The main() method is an entry point for the program. Here, we read two integer numbers from the user using the Scanner class. Then we performed subtraction between two integer numbers using the binSubtraction() method and printed the result.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to extract bytes from an integer (Hex... >>
<< Java program to find the sum of two numbers using ...