Python Program to Multiply Two Binary Numbers

Python Program to Multiply Two Binary Numbers

To multiply two binary numbers in Python, you can follow these steps:

  1. Take input of the two binary numbers as strings.
  2. Convert them into integers using the int() function with base 2.
  3. Multiply the integers.
  4. Convert the result back to a binary string using the bin() function.
  5. Print out the binary result.

Here's a Python program that does exactly that:

# Function to multiply two binary numbers def multiply_binary(bin1, bin2): # Convert binary numbers to decimal num1 = int(bin1, 2) num2 = int(bin2, 2) # Multiply the numbers product = num1 * num2 # Convert the product back to binary binary_product = bin(product)[2:] # Remove the '0b' prefix return binary_product # Input binary numbers binary1 = input("Enter the first binary number: ") binary2 = input("Enter the second binary number: ") # Multiply the binary numbers result = multiply_binary(binary1, binary2) # Print the result print(f"The product of {binary1} and {binary2} is {result}") 

Make sure the binary numbers are entered correctly, as the program doesn't handle invalid input. If you want to add error checking, you could include a function to verify that the input strings are valid binary numbers (i.e., they contain only 0 and 1 characters).


More Tags

web lint-staged git-push file-get-contents hamcrest maven-module google-chrome-devtools kivy-language codeigniter asp.net-mvc

More Programming Guides

Other Guides

More Programming Examples