3
\$\begingroup\$
  1. Given a decimal number I need to convert it into binary
  2. Given a binary number I need to convert it into decimal

After the conversion I need to perform some operation on it (for example, addition). I also need to print the result with a specified width.

Binary-Decimal:

n1 = int(input("Enter a binary number: "))
n2 = int(input("Enter a binary number: "))

# type cast to 'int' is done to provide width
decimalN1 = int("{0:d}".format(n1), 2)
decimalN2 = int("{0:d}".format(n2), 2)
decimalSum = int("{0:d}".format(n1 + n2), 2)

width = len(str(decimalSum))
print("max width = {}".format(width))

print ("{0:0{3}} + {1:0{3}} = {2:0{3}}".format(decimalN1, decimalN2, decimalSum, width))
print ("{0} + {1} = {2}".format(type(decimalN1), type(decimalN2), type(decimalSum)))

Decimal-Binary:

n1 = int(input("Enter a decimal number: "))
n2 = int(input("Enter a decimal number: "))

# type cast to 'int' is done to provide width
binaryN1 = int("{0:b}".format(n1))
binaryN2 = int("{0:b}".format(n2))
binarySum = int("{0:b}".format(n1 + n2))

width = (n1 + n2).bit_length()
print("max width = {}".format(width))

print ("{0:0{3}} + {1:0{3}} = {2:0{3}}".format(binaryN1, binaryN2, binarySum, width))
print ("{0} + {1} = {2}".format(type(binaryN1), type(binaryN2), type(binarySum)))

I want to know if there is any other (better) way of doing this. I know the bin() function could be used, but then it returns a string, so I cannot perform (integer) operation on it after the conversion.

\$\endgroup\$
  • 1
    \$\begingroup\$ Use bin() funtion that would return string, then use int() which is the Python standard built-in function to convert a string into an integer value and then perform your operations. \$\endgroup\$ – Abhishek Gupta Dec 29 '16 at 6:30
4
\$\begingroup\$

Rather than repeating the same logic you could make a couple of functions binary_to_decimal and decimal_to_binary.

def binary_to_decimal(num):
    return int("{0:d}".format(num), 2)

def decimal_to_binary(num):
    return int("{0:b}".format(num))

Whilst it doesn't have too big an impact on the readability of your code it abstracts the code enough for anyone passing by to understand what you mean when you're doing the string formatting. You could also change binary_to_decimal to use str rather than string formatting, as I don't think we're going to change to the binary form any time soon. I also thing your string formatting for changing to binary is better than using bin as you'd have to cut the first 0b off the output of bin, which would make the code more cryptic.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.