By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,095 Members | 1,586 Online
Bytes IT Community
+ Ask a Question
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
  1. class BinaryNumber:
  2.     '''A Binary Number Class'''
  3.     #pass
  4.     def __init__(self, bitString = ''):
  5.         '''Constructor'''
  6.         #pass
  7.         self._bits = bitString
  8.  
  9.     def __str__(self):
  10.         '''string representation'''
  11.         if self._bits:
  12.             return self._bits
  13.         else:
  14.             return '0'
  15.  
  16.     def __int__(self):
  17.         '''conversion'''
  18.         #pass
  19.         total = 0
  20.         for pos in range(len(self._bits)):
  21.             if self._bits[pos] == '1':
  22.                 total += 2 ** (len(self._bits) - 1 - pos)
  23.         return total
  24.  
  25.     def __add__(self, other):
  26.         '''addition: implementation of the + operator'''
  27.         pass
  28.  
I am not allowed to import math either.

Any help would be much appreciated! :]
Oct 15 '10 #1
Share this Question
Share on Google+
14 Replies


bvdet
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
  1.     def __add__(self, other):
  2.         '''addition: implementation of the + operator'''
  3.         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
  1. # Program: ex6_18.py
  2. # Authors: Robert Mineweaser
  3. #
  4. # This example is discussed in Chapter 6 of the book
  5. # Object-Oriented Programming in Python
  6. #
  7.  
  8. class BinaryNumber:
  9.     '''A Binary Number Class'''
  10.     #pass
  11.     def __init__(self, bitString = ''):
  12.         '''Constructor'''
  13.         #pass
  14.         self._bits = bitString
  15.  
  16.     def __str__(self):
  17.         '''string representation'''
  18.         if self._bits:
  19.             return self._bits
  20.         else:
  21.             return '0'
  22.  
  23.     def __int__(self):
  24.         '''conversion'''
  25.         #pass
  26.         total = 0
  27.         for pos in range(len(self._bits)):
  28.             if self._bits[pos] == '1':
  29.                 total += 2 ** (len(self._bits) - 1 - pos)
  30.         return total
  31.  
  32.     def __add__(self, other):
  33.         '''addition: implementation of the + operator'''
  34.         #pass
  35.         '''carry = 0
  36.         result = ''
  37.  
  38.         # Work from right to left.
  39.         for i in range(0, len(self._bits))[::-1]:
  40.             tmp = int(((a[i]) + int(b[i]) + carry)/2)
  41.             res = str(int(a[i]) + int(b[i]) + carry - 2 * tmp)
  42.             result += res
  43.             carry = tmp
  44.  
  45.         result = (result + str(carry))[::-1]
  46.         try:
  47.             return result[result.index('1'):]
  48.         except ValueError, ex:
  49.             return '0'
  50.               '''
  51.         return self.dec2bin((int(self)+int(other)))
  52.  
  53.     def __subtract__(self, other):
  54.         '''subtraction: implementation of the - operator'''     # Optional
  55.         pass
  56.  
  57.     def __lt__(self, other):
  58.         '''less: implementation of the < operator'''
  59.         #pass
  60.         if int(a) <= int(b):
  61.             return True
  62.         else:
  63.             return False
  64.  
  65.     def __gt__(self, other):
  66.         '''great: implementation of the > operator'''
  67.         #pass
  68.         if int(a) >= int(b):
  69.             return True
  70.         else:
  71.             return False
  72.  
  73.     def __eq__(self, other):
  74.         '''equal: implementation of the = operator'''
  75.         #pass
  76.         if int(a) == int(b):
  77.             return True
  78.         else:
  79.             return False
  80.  
  81.  
  82. if __name__ == '__main__':
  83.     a  = BinaryNumber('01111001')   # binary numbers must start with 0
  84.     b  = BinaryNumber('00110101')   # a = 121, b = 53
  85.     print 'a = ', a, int(a)
  86.     print 'b = ', b, int(b)
  87.  
  88.     print 'a + b', a + b, int(a + b)
  89.     #print 'a - b', a - b, int(a - b)    # optional
  90.  
  91.     print 'a < b', a < b
  92.     print 'a > b', a > b
  93.     print 'a == b', a == b
  94.  
  95. print 'Press the Enter key to finish'
  96.  
  97. raw_input()
  98.  
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

bvdet
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

bvdet
Expert Mod 2.5K+
P: 2,851
Modify the string returned by __add__ and use string formatting. Untested:
Expand|Select|Wrap|Line Numbers
  1. 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
  1. class BinaryNumber:
  2.     '''A Binary Number Class'''
  3.     #pass
  4.     def __init__(self, bitString = ''):
  5.         '''Constructor'''
  6.         #pass
  7.         self._bits = bitString
  8.  
  9.     def __str__(self):
  10.         '''string representation'''
  11.         if self._bits:
  12.             return self._bits
  13.         else:
  14.             return '0'
  15.  
  16.     def __int__(self):
  17.         '''conversion'''
  18.         #pass
  19.         total = 0
  20.         for pos in range(len(self._bits)):
  21.             if self._bits[pos] == '1':
  22.                 total += 2 ** (len(self._bits) - 1 - pos)
  23.         return total
  24.  
  25.     def __add__(self, other):
  26.         '''addition: implementation of the + operator'''
  27.         pass
  28.  
  29.     def __subtract__(self, other):
  30.         '''subtraction: implementation of the - operator'''     # Optional
  31.         pass
  32.  
  33.     def __lt__(self, other):
  34.         '''less: implementation of the < operator'''
  35.         #pass
  36.         if int(a) <= int(b):
  37.             return True
  38.         else:
  39.             return False
  40.  
  41.     def __gt__(self, other):
  42.         '''great: implementation of the > operator'''
  43.         #pass
  44.         if int(a) >= int(b):
  45.             return True
  46.         else:
  47.             return False
  48.  
  49.     def __eq__(self, other):
  50.         '''equal: implementation of the = operator'''
  51.         #pass
  52.         if int(a) == int(b):
  53.             return True
  54.         else:
  55.             return False
  56.  
  57. if __name__ == '__main__':
  58.     a  = BinaryNumber('01111001')   # binary numbers must start with 0
  59.     b  = BinaryNumber('00110101')   # a = 121, b = 53
  60.     print 'a = ', a, int(a)
  61.     print 'b = ', b, int(b)
  62.  
  63.     print 'a + b', a + b, int(a + b)
  64.     #print 'a - b', a - b, int(a - b)    # optional
  65.  
  66.     print 'a < b', a < b
  67.     print 'a > b', a > b
  68.     print 'a == b', a == b
  69.  
  70. print 'Press the Enter key to finish'
  71.  
  72. raw_input()
  73.  
Oct 16 '10 #7

bvdet
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

bvdet
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

bvdet
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

bvdet
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
  1. def binDigit[self,position]:
  2.     if position>len(self._bits):
  3.         return 0
  4.     else:
  5.         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
  1. def __add__[self,other]:
  2.     v=max([len(self._bits),len(other._bits)])+1
  3.     ans=''
  4.     carry=0
  5.     for i in range(1,v+1):
  6.         a=self.position(i)
  7.         b=self.position(i)
  8.         t=carry+int(a)+int(b)        
  9.         if t<=1:
  10.             carry=0
  11.         else:
  12.             carry=1        
  13.         if t%2==0:
  14.             ans='0'+ans
  15.         else:
  16.             ans='1'+ans
  17.     return BinaryNumber(ans)
  18.  
I haven't checked any of this, but it should give you some idea.
Oct 25 '10 #15

Post your reply

Sign in to post your reply or Sign up for a free account.