Open In App

C++ Program to Implement Half Subtractor

Last Updated : 15 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

A Half Subtractor is a digital logic circuit that is used to subtract two single-bit binary numbers. In this article, we will learn how to implement the half subtractor logic in C++.

What is a Half Subtractor?

As told earlier, half subtractor is a digital logic circuit that makes the use of logical gates to subtract two single bit binary numbers. It takes two numbers,

  • minuend: The number from which the other number is being subtracted.
  • subtrahend: The number being subtracted from minuend.

After applying half subtractor, we get two values,

  • Difference: It represents the result of the subtraction
  • Borrow: It indicates whether a borrow operation is needed for the subtraction of the two bits. Generally needed when minuend is smaller than subtrahend

Logical Expression of Half Subtractor

The logical expression for half subtractor is as follows:

Difference = A XOR B
Borrow = Ā AND B

Implementation of Half Subtractor in C++

Using the logical expression, we can easily implement the half subtractor in C++. We can use both bitwise or logical operators for the implementation but the bitwise operators are recommended because they can be extended to the multi-digit binary numbers.

C++
// C++ program to implement half subtractor
#include <bits/stdc++.h>
using namespace std;

void halfSub(int A, int B){
  
    // Create difference and borrow variables
    int diff, bow;
  
    // Calculating the difference by bitwise XOR
    diff = A ^ B;
 
    // Calculate the borrow using biwise AND
  	// and NOT
    A = ~A;
    bow = A & B;
 
    cout << "Difference = " << diff << endl;
    cout << "Borrow = " << bow;
}

int main() {
    int A = 1;
    int B = 1;
  
    // Calling half subtrator for A and B
    halfSub(A, B);
    return 0;
}

Output
Difference = 0
Borrow = 0




Practice Tags :

Similar Reads