440,095 Members | 1,586 Online
Need help? Post your question and get tips & solutions from a community of 440,095 IT Pros & Developers. It's quick & easy.

# How do you do binary addition on python?

 P: 32 I'm having trouble trying to add these together correctly. I have kind of ran into a brick wall. I have gotten it converted and that's it as of now. My Code: Expand|Select|Wrap|Line Numbers class BinaryNumber:     '''A Binary Number Class'''     #pass     def __init__(self, bitString = ''):         '''Constructor'''         #pass         self._bits = bitString       def __str__(self):         '''string representation'''         if self._bits:             return self._bits         else:             return '0'       def __int__(self):         '''conversion'''         #pass         total = 0         for pos in range(len(self._bits)):             if self._bits[pos] == '1':                 total += 2 ** (len(self._bits) - 1 - pos)         return total       def __add__(self, other):         '''addition: implementation of the + operator'''         pass   I am not allowed to import math either. Any help would be much appreciated! :] Oct 15 '10 #1
14 Replies

 Expert Mod 2.5K+ P: 2,851 All you need is a conversion of a decimal integer to binary. Then your magic method __add__ would be: Expand|Select|Wrap|Line Numbers     def __add__(self, other):         '''addition: implementation of the + operator'''         return self.dec2bin((int(self)+int(other))) Have you tried to write code for it? Oct 15 '10 #2

 P: 32 I have tried a similar code that used "import math" and tried changing it to get it to work, but it didn't. This is all of my code as of right now for my project: Expand|Select|Wrap|Line Numbers # Program: ex6_18.py # Authors: Robert Mineweaser # # This example is discussed in Chapter 6 of the book # Object-Oriented Programming in Python #   class BinaryNumber:     '''A Binary Number Class'''     #pass     def __init__(self, bitString = ''):         '''Constructor'''         #pass         self._bits = bitString       def __str__(self):         '''string representation'''         if self._bits:             return self._bits         else:             return '0'       def __int__(self):         '''conversion'''         #pass         total = 0         for pos in range(len(self._bits)):             if self._bits[pos] == '1':                 total += 2 ** (len(self._bits) - 1 - pos)         return total       def __add__(self, other):         '''addition: implementation of the + operator'''         #pass         '''carry = 0         result = ''           # Work from right to left.         for i in range(0, len(self._bits))[::-1]:             tmp = int(((a[i]) + int(b[i]) + carry)/2)             res = str(int(a[i]) + int(b[i]) + carry - 2 * tmp)             result += res             carry = tmp           result = (result + str(carry))[::-1]         try:             return result[result.index('1'):]         except ValueError, ex:             return '0'               '''         return self.dec2bin((int(self)+int(other)))       def __subtract__(self, other):         '''subtraction: implementation of the - operator'''     # Optional         pass       def __lt__(self, other):         '''less: implementation of the < operator'''         #pass         if int(a) <= int(b):             return True         else:             return False       def __gt__(self, other):         '''great: implementation of the > operator'''         #pass         if int(a) >= int(b):             return True         else:             return False       def __eq__(self, other):         '''equal: implementation of the = operator'''         #pass         if int(a) == int(b):             return True         else:             return False     if __name__ == '__main__':     a  = BinaryNumber('01111001')   # binary numbers must start with 0     b  = BinaryNumber('00110101')   # a = 121, b = 53     print 'a = ', a, int(a)     print 'b = ', b, int(b)       print 'a + b', a + b, int(a + b)     #print 'a - b', a - b, int(a - b)    # optional       print 'a < b', a < b     print 'a > b', a > b     print 'a == b', a == b   print 'Press the Enter key to finish'   raw_input()   If you couldn't tell, subtraction is optional and I commented the code i tried to change to get to work. Any advice on what I could do to fix this. Oct 15 '10 #3

 Expert Mod 2.5K+ P: 2,851 Function dec2bin() would be a class method. Check out this thread. Oct 16 '10 #4

 P: 32 Alright. After it is added together, I need my output to show as " a + b (binary result) (decimal result). How would I make it add them together and have it show that as the result of the two? Oct 16 '10 #5

 Expert Mod 2.5K+ P: 2,851 Modify the string returned by __add__ and use string formatting. Untested: Expand|Select|Wrap|Line Numbers return "%s + %s (%s) (%s)" % (self, other, self.dec2bin((int(self)+int(other))), (int(self)+int(other))) Oct 16 '10 #6

 P: 32 I am still a little confused. All I need to do is add 2 binary numbers together and have the output be " a + b (binary result) (decimal result) ". The conversion was to just give me the decimal result. So how would I go about adding this all together to get the given output, " a + b (binary result) (decimal result) " ? If you don't understand what I am trying to ask please feel free to tell me. This was my original code for " __add__" without any additions from me: Expand|Select|Wrap|Line Numbers class BinaryNumber:     '''A Binary Number Class'''     #pass     def __init__(self, bitString = ''):         '''Constructor'''         #pass         self._bits = bitString       def __str__(self):         '''string representation'''         if self._bits:             return self._bits         else:             return '0'       def __int__(self):         '''conversion'''         #pass         total = 0         for pos in range(len(self._bits)):             if self._bits[pos] == '1':                 total += 2 ** (len(self._bits) - 1 - pos)         return total       def __add__(self, other):         '''addition: implementation of the + operator'''         pass       def __subtract__(self, other):         '''subtraction: implementation of the - operator'''     # Optional         pass       def __lt__(self, other):         '''less: implementation of the < operator'''         #pass         if int(a) <= int(b):             return True         else:             return False       def __gt__(self, other):         '''great: implementation of the > operator'''         #pass         if int(a) >= int(b):             return True         else:             return False       def __eq__(self, other):         '''equal: implementation of the = operator'''         #pass         if int(a) == int(b):             return True         else:             return False   if __name__ == '__main__':     a  = BinaryNumber('01111001')   # binary numbers must start with 0     b  = BinaryNumber('00110101')   # a = 121, b = 53     print 'a = ', a, int(a)     print 'b = ', b, int(b)       print 'a + b', a + b, int(a + b)     #print 'a - b', a - b, int(a - b)    # optional       print 'a < b', a < b     print 'a > b', a > b     print 'a == b', a == b   print 'Press the Enter key to finish'   raw_input()   Oct 16 '10 #7

 Expert Mod 2.5K+ P: 2,851 See my first post in this thread. Oct 16 '10 #8

 P: 32 Yes, but even when I put that in, I get an error, "AttributeError: BinaryNumber instance has no attribute 'dec2bin'". How exactly would I have to make this code to look to get it to add the binary numbers together correctly and have it give me the output, "a + b (binary result) (decimal result)" ? Oct 16 '10 #9

 Expert Mod 2.5K+ P: 2,851 You must add a BinaryNumber method dec2bin(). The method must return the decimal number converted to binary. Oct 16 '10 #10

 P: 32 Is this the only way to do it? Or is there another way possible? If not, how would I go about doing this? Oct 16 '10 #11

 Expert Mod 2.5K+ P: 2,851 That is the way I would do it, because that's the easiest for me. There are other ways though. You can write the code to do binary addition and subtraction in methods __add__() and __sub__() respectively. Check out this website. Oct 16 '10 #12

 P: 32 I understand the concepts of binary addition, but I just have trouble putting it into code. How would I write the code for binary addition in the method __add__? Oct 16 '10 #13

 Expert Mod 2.5K+ P: 2,851 I am sorry, but I cannot write the code for you. Please show some effort on your own, then we can help. Since you understand the concepts of binary addition, you may know more than me about it. Even if you do the binary addition, I think the code should go into a separate function. Oct 18 '10 #14

 Expert 100+ P: 391 Hi It seems to me that, since you're implementing your own version of this, you might as well do the addition in binary. Your bitString is just a string of 1s and 0s, if I'm not mistaken? So, I would first implement something that returns a single digit in a given position. Something like: Expand|Select|Wrap|Line Numbers def binDigit[self,position]:     if position>len(self._bits):         return 0     else:         return self._bits[-position] if self._bits="101", then position[1] = 1, position[2]=0, position[3]=1 and position[4]=0 etc. Now create something that does the addition bit by bit (literally!): Expand|Select|Wrap|Line Numbers def __add__[self,other]:     v=max([len(self._bits),len(other._bits)])+1     ans=''     carry=0     for i in range(1,v+1):         a=self.position(i)         b=self.position(i)         t=carry+int(a)+int(b)                 if t<=1:             carry=0         else:             carry=1                 if t%2==0:             ans='0'+ans         else:             ans='1'+ans     return BinaryNumber(ans)   I haven't checked any of this, but it should give you some idea. Oct 25 '10 #15