Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Binary Coded Decimal (BCD) Addition?
3.
Approach for BCD Addition
4.
Implementation of BCD Addition 
4.1.
BCD Addition in C++
4.2.
BCD Addition in Python
4.3.
BCD Addition in Java
4.3.1.
Time and Space Complexity
5.
Frequently Asked Questions
5.1.
What is the purpose of BCD addition? 
5.2.
What are the rules for BCD addition?
5.3.
In which scenarios we need to add +6 for BCD addition result?
6.
Conclusion
Last Updated: Mar 27, 2024
Medium

Binary Coded Decimal (BCD) Addition

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Hey Ninjas! Ready to learn some more? Today we will be covering BCD addition. It is a way of binary addition known for its efficiency and portability, making them popular among programmers.

bcd addition

We know that every number can be represented uniquely in binary format. To be precise, we can represent all numbers up to 1e9 as a unique representation in 32 bits. It leads to another ecosystem of number representation that supports all mathematical operations. They are extremely interesting to work on. One such addition method is BCD which stands for Binary Coded Decimal addition.

You can also read about - Shift Registers in Digital Electronics and Difference Between Jfet and Mosfet

What is Binary Coded Decimal (BCD) Addition?

Binary Coded Decimal Addition is a well-defined way to add two decimal numbers represented in their corresponding binary format. On a simpler note, BCD addition refers to concatenating the binary representation of each digit obtained after the decimal addition of two numbers.

For example: Consider the numbers A = 20 and B = 40. The summation of A and B returns 60. The digits 60 are 6 and 0. So all we need to do is add the binary representation of 6 and 0. So we need to add the strings 0110(6) and 0000(0). Hence 01100000 is the desired output.

This method is used in electronic circuits requiring decimal arithmetic, such as calculators, digital clocks, and industrial control systems.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Approach for BCD Addition

After understanding the problem statement, we may adopt various possible solutions to code the BCD approach. 
 

  • One possible solution is using a hashmap to store the string representation of all digits.
     
  • We add the input numbers and store their digits in a vector. We reverse the vector to obtain the correct order for BCD addition. 
     
  • Finally, we replace the digits in the vector with their string representations and obtain the required answer.
     
  • We may also replace the hashmap with a simple array, as represented in the Java` & python code below.

Also see,  what is middleware

Implementation of BCD Addition 

We will see the implementation of BCD addition in various languages.

BCD Addition in C++

The implementation of BCD addition in C++ goes as follows:

#include <bits/stdc++.h>
using namespace std;
string BCD(int x,int y)
{
    int num = x+y;
    vector<int> vec;
    map<int,string>mpp;
    mpp[0]="0000";
    mpp[1]="0001";
    mpp[2]="0010";
    mpp[3]="0011";
    mpp[4]="0100";
    mpp[5]="0101";
    mpp[6]="0110";
    mpp[7]="0111";
    mpp[8]="1000";
    mpp[9]="1001";
    string ans="";
    while(num>0)
    {
        int d=num%10;
        vec.push_back(d);
        num/=10;
    }
    reverse(vec.begin(),vec.end());
    for(auto x:vec)
    {
        ans+=mpp[x];
    }
    return ans;
}
// Driver Code
int main()
{
	int num1=10;
	int num2=20;
	cout << BCD(num1,num2);
	return 0;
}


Output

00110000

The C++ code explanation goes as follows:

  • The above code calls the function BCD addition for the designed task. 
     
  • In this function, we precompute and store the binary string representation of all digits in a hashmap. 
     
  • Now, we store all digits of the number in a vector. 
     
  • We reverse the vector to fix the order as digits were earlier generated in the opposite order. 
     
  • In the last step, we concatenate the strings in order and return the final string.

BCD Addition in Python

The implementation of BCD addition in Python goes as follows:

def bcd(n1, n2):
    p = n1 + n2
    s = str(p)
    n = len(s)
    ans = ""
    mx = ""
    t = ["0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001"]
    for i in range(len(s)):
        mx = t[int(s[i])]
        ans+=mx


    return ans


a = 20
b = 30
print(bcd(a, b))


Output

00110000

BCD Addition in Java

The implementation of BCD addition in Java goes as follows:

public class Main
{
    public static String BCD(int num1, int num2)
 {
    // Calculate sum  
    int p = num1 + num2 ;
    String sumString = String.valueOf(p);
    int n = sumString.length();
   	// To store the final result
    String ans = "";
// Array containing all the binary values
    String vec[] = { "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001" };
    for (int i = 0; i < n; i++) 
    {
       String mx = vec[sumString.charAt(i) - '0'];
       ans += mx;
     }
    // Returning ans
     return ans;
 }

public static void main(String[] args) 
 {
    int a=10;
    int b=20;
    System.out.println(BCD(a,b));
 }
}


Output

00110000


Explanation

In the above codes, we call the BCD function with 2 numbers to be added as the parameter.

The BCD function adds the two numbers and performs string concatenation of the BCD representation of the digits of the summation. These binary representations are stored in the string vector. The final string ans contains the resultant output.

Time and Space Complexity

It is important to know the time and space complexity of the code we have discussed above. Below is the calculated time and space complexity for BCD addition program.

Time Complexity: O(len(num1+num2)). The time complexity of the above code is O(len(num1+num2)) because, in the worst case, the summation of 2 numbers can be several lengths equal to the sum of lengths of the 2 numbers. Hence the final length of the string is equal to 4*(length of summation) because the size of each string in the hashmap is 4.

Space Complexity: O(1). The space complexity is O(1) because we are not using any major container to store data in the above codes. The hashmap always contains only ten elements; hence it will be considered constant space.

Frequently Asked Questions

What is the purpose of BCD addition? 

In digital circuits and microcontrollers, BCD addition is commonly used to perform arithmetic operations with decimal numbers. 

What are the rules for BCD addition?

The rules for BCD addition are as follows: Perform binary addition on each pair of BCD digits. If the result is greater than 9, add 6 to the result to correct the BCD representation. Carry-over digits are handled as usual.

In which scenarios we need to add +6 for BCD addition result?

In BCD addition, you may need to add +6 to the result under certain scenarios to correct for binary-coded decimal arithmetic rules. The reason for adding +6 is to adjust the result when it exceeds 9 in any BCD digit during addition. In BCD, each digit represents a decimal number from 0 to 9 using four binary bits. When adding two BCD digits, the result can exceed 9, which is the maximum value for a BCD digit.

Conclusion

The article was clear enough to explain the working and implementation of BCD addition in detail. This is an important algorithm often used in calculators and digital watches.

Demultiplexer

Binary to Octal conversion

Binary Numbers of N digits

All Binary Numbers in range from L to R

You may also refer to our Guided Path on Code Studios to enhance your skill set on DSA and many more. Check out essential interview questions, practice our available mock tests, and more!

Live masterclass