Need help in adding binary numbers in python

user3246901 picture user3246901 · Jan 29, 2014 · Viewed 58.7k times · Source

If I have 2 numbers in binary form as a string, and I want to add them I will do it digit by digit, from the right most end. So 001 + 010 = 011 But suppose I have to do 001+001, how should I create a code to figure out how to take carry over responses?

Answer

Mostly Harmless picture Mostly Harmless · Jan 29, 2014

bin and int are very useful here:

a = '001'
b = '011'

c = bin(int(a,2) + int(b,2))
# 0b100

int allows you to specify what base the first argument is in when converting from a string (in this case two), and bin converts a number back to a binary string.