Welcome to Coding 4 Programming

Addition of Two Binary Numbers | Function | Python

 

Addition of Two Binary Numbers entered by the user in Python Programming Language through the concept of Function. 

  • Coding for the above Program.

  1. def add_bn(x, y):
  2.        max_len = max(len(x), len(y))
  3.        x = x.zfill(max_len)
  4.        y = y.zfill(max_len)
  5.        result = ''
  6.        carry = 0
  7.        for i in range(max_len - 1, -1, -1):
  8.               r = carry
  9.               r += 1 if x[i] == '1' else 0
  10.               r += 1 if y[i] == '1' else 0
  11.               result = ('1' if r % 2 == 1 else '0') + result
  12.               carry = 0 if r < 2 else 1        
  13.        if carry !=0 : result = '1' + result   
  14.        return result.zfill(max_len)
  15. n1=input("Enter First Binary Number=")
  16. n2=input("Enter Second Binary Number=")
  17. print(f"Addition of {n1} and {n2} is {add_bn(n1, n2)}") 
  • Output of the Temperature Conversion Program.

    Addition Of Binary
    Output of Addition of Binary Numbers in Python


    Notes:

    • If you have any problem related to this program. Please do comment your Problem or Mail us.
    • For illustrating the any concept you can comment by line number.
    • Thank you! For more programs do regular visit to Coding 4 Programming.


    Comments

    Popular Posts