Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help in adding binary numbers in python

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?

like image 349
user3246901 Avatar asked Jan 29 '14 01:01

user3246901


1 Answers

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.

like image 75
Mostly Harmless Avatar answered Oct 19 '22 04:10

Mostly Harmless