How do you do binary addition on python?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Fuugie
    New Member
    • Sep 2010
    • 32

    How do you do binary addition on python?

    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:
    Code:
    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! :]
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    All you need is a conversion of a decimal integer to binary. Then your magic method __add__ would be:
    Code:
        def __add__(self, other):
            '''addition: implementation of the + operator'''
            return self.dec2bin((int(self)+int(other)))
    Have you tried to write code for it?

    Comment

    • Fuugie
      New Member
      • Sep 2010
      • 32

      #3
      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:
      Code:
      # 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.

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        Function dec2bin() would be a class method. Check out this thread.

        Comment

        • Fuugie
          New Member
          • Sep 2010
          • 32

          #5
          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?

          Comment

          • bvdet
            Recognized Expert Specialist
            • Oct 2006
            • 2851

            #6
            Modify the string returned by __add__ and use string formatting. Untested:
            Code:
            return "%s + %s (%s) (%s)" % (self, other, self.dec2bin((int(self)+int(other))), (int(self)+int(other)))

            Comment

            • Fuugie
              New Member
              • Sep 2010
              • 32

              #7
              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:
              Code:
              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()

              Comment

              • bvdet
                Recognized Expert Specialist
                • Oct 2006
                • 2851

                #8
                See my first post in this thread.

                Comment

                • Fuugie
                  New Member
                  • Sep 2010
                  • 32

                  #9
                  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)" ?

                  Comment

                  • bvdet
                    Recognized Expert Specialist
                    • Oct 2006
                    • 2851

                    #10
                    You must add a BinaryNumber method dec2bin(). The method must return the decimal number converted to binary.

                    Comment

                    • Fuugie
                      New Member
                      • Sep 2010
                      • 32

                      #11
                      Is this the only way to do it? Or is there another way possible? If not, how would I go about doing this?

                      Comment

                      • bvdet
                        Recognized Expert Specialist
                        • Oct 2006
                        • 2851

                        #12
                        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.

                        Comment

                        • Fuugie
                          New Member
                          • Sep 2010
                          • 32

                          #13
                          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__?

                          Comment

                          • bvdet
                            Recognized Expert Specialist
                            • Oct 2006
                            • 2851

                            #14
                            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.
                            Last edited by bvdet; Oct 18 '10, 04:54 AM. Reason: Add comment

                            Comment

                            • Glenton
                              Recognized Expert Contributor
                              • Nov 2008
                              • 391

                              #15
                              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:
                              Code:
                              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!):
                              Code:
                              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.

                              Comment

                              Working...