Posted on by Kalkicode
Code Bit Logic

Subtract two numbers using bitwise operators

In this article, we will explore how to subtract two numbers using bitwise operators. The bitwise operators work at the individual bit level of numbers, allowing us to perform various arithmetic operations more efficiently. The problem statement is to create a function that takes two integers as input and returns their difference using bitwise operations.

Introduction

Subtraction is a fundamental arithmetic operation that finds the difference between two numbers. Traditionally, subtraction is performed by complementing one of the numbers and then adding it to the other. However, we can achieve subtraction using bitwise operators, which are low-level operations that manipulate individual bits of numbers.

Problem Statement

Given two integers, a and b, we need to calculate the value of (a - b) using bitwise operators.

Explanation with Example

Let's understand the subtraction process using an example:

Suppose we want to find the difference between a = 7 and b = 3. The traditional subtraction method would be a - b = 7 - 3 = 4.

Pseudocode

To subtract two numbers using bitwise operators, we will use the following pseudocode:

function subtractNum(a, b):
    while b is not 0:
        temp = complement of a AND b left-shifted by 1
        a = a XOR b
        b = temp
    return a

Algorithm Explanation

  1. Start with the given two numbers a and b.
  2. Enter a loop that continues until b becomes 0.
  3. Inside the loop: a. Calculate the complement of a AND b (bitwise AND operation) and then left-shift the result by 1. Store this value in a temporary variable temp. b. Update a by performing a bitwise XOR operation between a and b. c. Update b to the value of temp.
  4. After the loop ends, the final value of a will be the result of the subtraction.

Explanation of the Pseudocode

Let's go through the pseudocode step by step using the example a = 7 and b = 3:

Step 1: Initialize a = 7 and b = 3.

Step 2: Enter the loop.

Step 3a: Calculate the complement of a AND b: complement(7) AND 3 = 0b11111000 AND 0b00000011 = 0b00000000. Then, left-shift the result by 1: 0b00000000 << 1 = 0b00000000.

Step 3b: Update a using the XOR operation: 7 XOR 3 = 0b00000111 XOR 0b00000011 = 0b00000100. Now, a becomes 4.

Step 3c: Update b to the value of temp: b = 0b00000000, which is 0.

Step 4: Exit the loop as b is now 0.

Resultant Output Explanation

The final value of a after the loop is 4. So, (7 - 3) = 4, which is the correct output.

Code Solution

Here given code implementation process.

// C Program 
// Subtract two numbers using bitwise operators
#include <stdio.h>

// Perform subtract of two numbers
void subtractNum(int a, int b)
{
	// Display given number
	printf("\n Number a : %d", a);
	printf("\n Number b : %d", b);
	printf("\n Subtract ((%d)-(%d))", a, b);
	int temp = 0;
	// Subtract of two numbers
	while (b != 0)
	{
		temp = ((~a) & b) << 1;
		a = a ^ b;
		b = temp;
	}
	// Display calculated result
	printf("\n Output :  %d\n", a);
}
int main(int argc, char const *argv[])
{
	// Test Cases
	subtractNum(12, -31);
	subtractNum(3, 4);
	subtractNum(-1, -4);
	subtractNum(12, 4);
	return 0;
}

Output

 Number a : 12
 Number b : -31
 Subtract ((12)-(-31))
 Output :  43

 Number a : 3
 Number b : 4
 Subtract ((3)-(4))
 Output :  -1

 Number a : -1
 Number b : -4
 Subtract ((-1)-(-4))
 Output :  3

 Number a : 12
 Number b : 4
 Subtract ((12)-(4))
 Output :  8
/*
  Java Program 
  Subtract two numbers using bitwise operators
*/
public class Subtraction
{
	// Perform subtract of two numbers
	public void subtractNum(int a, int b)
	{
		// Display given number
		System.out.print("\n Number a : " + a);
		System.out.print("\n Number b : " + b);
		System.out.print("\n Subtract ((" + a + ")-(" + b + "))");
		int temp = 0;
		// Subtract of two numbers
		while (b != 0)
		{
			temp = ((~a) & b) << 1;
			a = a ^ b;
			b = temp;
		}
		// Display calculated result
		System.out.print("\n Output : " + a + "\n");
	}
	public static void main(String[] args)
	{
		Subtraction task = new Subtraction();
		// Test Cases
		task.subtractNum(12, -31);
		task.subtractNum(3, 4);
		task.subtractNum(-1, -4);
		task.subtractNum(12, 4);
	}
}

Output

 Number a : 12
 Number b : -31
 Subtract ((12)-(-31))
 Output : 43

 Number a : 3
 Number b : 4
 Subtract ((3)-(4))
 Output : -1

 Number a : -1
 Number b : -4
 Subtract ((-1)-(-4))
 Output : 3

 Number a : 12
 Number b : 4
 Subtract ((12)-(4))
 Output : 8
// Include header file
#include <iostream>
using namespace std;

/*
  C++ Program 
  Subtract two numbers using bitwise operators
*/

class Subtraction
{
	public:
		// Perform subtract of two numbers
		void subtractNum(int a, int b)
		{
			// Display given number
			cout << "\n Number a : " << a;
			cout << "\n Number b : " << b;
			cout << "\n Subtract ((" << a << ")-(" << b << "))";
			int temp = 0;
			// Subtract of two numbers
			while (b != 0)
			{
				temp = ((~a) & b) << 1;
				a = a ^ b;
				b = temp;
			}
			// Display calculated result
			cout << "\n Output : " << a << "\n";
		}
};
int main()
{
	Subtraction task = Subtraction();
	// Test Cases
	task.subtractNum(12, -31);
	task.subtractNum(3, 4);
	task.subtractNum(-1, -4);
	task.subtractNum(12, 4);
	return 0;
}

Output

 Number a : 12
 Number b : -31
 Subtract ((12)-(-31))
 Output : 43

 Number a : 3
 Number b : 4
 Subtract ((3)-(4))
 Output : -1

 Number a : -1
 Number b : -4
 Subtract ((-1)-(-4))
 Output : 3

 Number a : 12
 Number b : 4
 Subtract ((12)-(4))
 Output : 8
// Include namespace system
using System;
/*
  C# Program 
  Subtract two numbers using bitwise operators
*/
public class Subtraction
{
	// Perform subtract of two numbers
	public void subtractNum(int a, int b)
	{
		// Display given number
		Console.Write("\n Number a : " + a);
		Console.Write("\n Number b : " + b);
		Console.Write("\n Subtract ((" + a + ")-(" + b + "))");
		int temp = 0;
		// Subtract of two numbers
		while (b != 0)
		{
			temp = ((~a) & b) << 1;
			a = a ^ b;
			b = temp;
		}
		// Display calculated result
		Console.Write("\n Output : " + a + "\n");
	}
	public static void Main(String[] args)
	{
		Subtraction task = new Subtraction();
		// Test Cases
		task.subtractNum(12, -31);
		task.subtractNum(3, 4);
		task.subtractNum(-1, -4);
		task.subtractNum(12, 4);
	}
}

Output

 Number a : 12
 Number b : -31
 Subtract ((12)-(-31))
 Output : 43

 Number a : 3
 Number b : 4
 Subtract ((3)-(4))
 Output : -1

 Number a : -1
 Number b : -4
 Subtract ((-1)-(-4))
 Output : 3

 Number a : 12
 Number b : 4
 Subtract ((12)-(4))
 Output : 8
<?php
/*
  Php Program 
  Subtract two numbers using bitwise operators
*/
class Subtraction
{
	// Perform subtract of two numbers
	public	function subtractNum($a, $b)
	{
		// Display given number
		echo "\n Number a : ". $a;
		echo "\n Number b : ". $b;
		echo "\n Subtract ((". $a .")-(". $b ."))";
		$temp = 0;
		// Subtract of two numbers
		while ($b != 0)
		{
			$temp = ((~$a) & $b) << 1;
			$a = $a ^ $b;
			$b = $temp;
		}
		// Display calculated result
		echo "\n Output : ". $a ."\n";
	}
}

function main()
{
	$task = new Subtraction();
	// Test Cases
	$task->subtractNum(12, -31);
	$task->subtractNum(3, 4);
	$task->subtractNum(-1, -4);
	$task->subtractNum(12, 4);
}
main();

Output

 Number a : 12
 Number b : -31
 Subtract ((12)-(-31))
 Output : 43

 Number a : 3
 Number b : 4
 Subtract ((3)-(4))
 Output : -1

 Number a : -1
 Number b : -4
 Subtract ((-1)-(-4))
 Output : 3

 Number a : 12
 Number b : 4
 Subtract ((12)-(4))
 Output : 8
/*
  Node Js Program 
  Subtract two numbers using bitwise operators
*/
class Subtraction
{
	// Perform subtract of two numbers
	subtractNum(a, b)
	{
		// Display given number
		process.stdout.write("\n Number a : " + a);
		process.stdout.write("\n Number b : " + b);
		process.stdout.write("\n Subtract ((" + a + ")-(" + b + "))");
		var temp = 0;
		// Subtract of two numbers
		while (b != 0)
		{
			temp = ((~a) & b) << 1;
			a = a ^ b;
			b = temp;
		}
		// Display calculated result
		process.stdout.write("\n Output : " + a + "\n");
	}
}

function main()
{
	var task = new Subtraction();
	// Test Cases
	task.subtractNum(12, -31);
	task.subtractNum(3, 4);
	task.subtractNum(-1, -4);
	task.subtractNum(12, 4);
}
main();

Output

 Number a : 12
 Number b : -31
 Subtract ((12)-(-31))
 Output : 43

 Number a : 3
 Number b : 4
 Subtract ((3)-(4))
 Output : -1

 Number a : -1
 Number b : -4
 Subtract ((-1)-(-4))
 Output : 3

 Number a : 12
 Number b : 4
 Subtract ((12)-(4))
 Output : 8
/*
  Scala Program 
  Subtract two numbers using bitwise operators
*/
class Subtraction
{
	// Perform subtract of two numbers
	def subtractNum(n1: Int, n2: Int): Unit = {
      	var a = n1;
      	var b = n2;
		// Display given number
		print("\n Number a : " + a);
		print("\n Number b : " + b);
		print("\n Subtract ((" + a + ")-(" + b + "))");
		var temp: Int = 0;
		// Subtract of two numbers
		while (b != 0)
		{
			temp = ((~a) & b) << 1;
			a = a ^ b;
			b = temp;
		}
		// Display calculated result
		print("\n Output : " + a + "\n");
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
		var task: Subtraction = new Subtraction();
		// Test Cases
		task.subtractNum(12, -31);
		task.subtractNum(3, 4);
		task.subtractNum(-1, -4);
		task.subtractNum(12, 4);
	}
}

Output

 Number a : 12
 Number b : -31
 Subtract ((12)-(-31))
 Output : 43

 Number a : 3
 Number b : 4
 Subtract ((3)-(4))
 Output : -1

 Number a : -1
 Number b : -4
 Subtract ((-1)-(-4))
 Output : 3

 Number a : 12
 Number b : 4
 Subtract ((12)-(4))
 Output : 8
/*
  Swift 4 Program 
  Subtract two numbers using bitwise operators
*/
class Subtraction
{
	// Perform subtract of two numbers
	func subtractNum(_ n1: Int, _ n2:  Int)
	{
      	var a = n1;
      	var b = n2;
		// Display given number
		print("\n Number a : ", a, terminator: "");
		print("\n Number b : ", b, terminator: "");
		print("\n Subtract ((", a ,")-(", b ,"))", terminator: "");
		var temp: Int = 0;
		// Subtract of two numbers
		while (b  != 0)
		{
			temp = ((~a) & b) << 1;
			a = a ^ b;
			b = temp;
		}
		// Display calculated result
		print("\n Output : ", a );
	}
}
func main()
{
	let task: Subtraction = Subtraction();
	// Test Cases
	task.subtractNum(12, -31);
	task.subtractNum(3, 4);
	task.subtractNum(-1, -4);
	task.subtractNum(12, 4);
}
main();

Output

 Number a :  12
 Number b :  -31
 Subtract (( 12 )-( -31 ))
 Output :  43

 Number a :  3
 Number b :  4
 Subtract (( 3 )-( 4 ))
 Output :  -1

 Number a :  -1
 Number b :  -4
 Subtract (( -1 )-( -4 ))
 Output :  3

 Number a :  12
 Number b :  4
 Subtract (( 12 )-( 4 ))
 Output :  8
/*
  Kotlin Program 
  Subtract two numbers using bitwise operators
*/
class Subtraction
{
	// Perform subtract of two numbers
	fun subtractNum(n1: Int, n2: Int): Unit
	{
      	var a = n1;
      	var b = n2;
		// Display given number
		print("\n Number a : " + a);
		print("\n Number b : " + b);
		print("\n Subtract ((" + a + ")-(" + b + "))");
		var temp: Int ;
		// Subtract of two numbers
		while (b != 0)
		{
			temp = ((a.inv()) and b) shl 1;
			a = a xor b;
			b = temp;
		}
		// Display calculated result
		print("\n Output : " + a + "\n");
	}
}
fun main(args: Array <String> ): Unit
{
	var task: Subtraction = Subtraction();
	// Test Cases
	task.subtractNum(12, -31);
	task.subtractNum(3, 4);
	task.subtractNum(-1, -4);
	task.subtractNum(12, 4);
}

Output

 Number a : 12
 Number b : -31
 Subtract ((12)-(-31))
 Output : 43

 Number a : 3
 Number b : 4
 Subtract ((3)-(4))
 Output : -1

 Number a : -1
 Number b : -4
 Subtract ((-1)-(-4))
 Output : 3

 Number a : 12
 Number b : 4
 Subtract ((12)-(4))
 Output : 8
fn main()
{
	// Test Cases
	subtract_num(12, -31);
	subtract_num(3, 4);
	subtract_num(-1, -4);
	subtract_num(12, 4);
}
fn subtract_num(n1: i32, n2: i32)
{
    let mut a = n1;
  	let mut b = n2;
	// Display given number
	print!("\n Number a : {}", a);
	print!("\n Number b : {}", b);
	print!("\n Subtract (({})-({}))", a, b);
	let mut temp: i32 ;
	// Subtract of two numbers
	while b != 0
	{
		temp = ((!a) & b) << 1;
		a = a ^ b;
		b = temp;
	}
	// Display calculated result
	print!("\n Output : {}\n", a);
}

Output

 Number a : 12
 Number b : -31
 Subtract ((12)-(-31))
 Output : 43

 Number a : 3
 Number b : 4
 Subtract ((3)-(4))
 Output : -1

 Number a : -1
 Number b : -4
 Subtract ((-1)-(-4))
 Output : 3

 Number a : 12
 Number b : 4
 Subtract ((12)-(4))
 Output : 8

Time Complexity

The time complexity of the bitwise subtraction algorithm is O(k), where k is the number of bits in the larger of the two input numbers a and b. In the worst case, the loop will run until b becomes 0, and the number of iterations depends on the number of bits in b. Hence, the time complexity is linear with respect to the number of bits.

Conclusion

In this article, we explored how to subtract two numbers using bitwise operators. We discussed the problem statement, provided pseudocode and an algorithm explanation with a suitable example. Finally, we explained the resultant output and analyzed the time complexity of the algorithm. By leveraging bitwise operations, we can efficiently perform subtraction and other arithmetic operations at the bit level, making our code more optimized and faster.

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment