473,512 Members | 15,196 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How do you do binary addition on python?

32 New Member
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
14 13447
bvdet
2,851 Recognized Expert Moderator Specialist
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
Fuugie
32 New Member
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
2,851 Recognized Expert Moderator Specialist
Function dec2bin() would be a class method. Check out this thread.
Oct 16 '10 #4
Fuugie
32 New Member
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
2,851 Recognized Expert Moderator Specialist
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
Fuugie
32 New Member
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
2,851 Recognized Expert Moderator Specialist
See my first post in this thread.
Oct 16 '10 #8
Fuugie
32 New Member
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
2,851 Recognized Expert Moderator Specialist
You must add a BinaryNumber method dec2bin(). The method must return the decimal number converted to binary.
Oct 16 '10 #10
Fuugie
32 New Member
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
2,851 Recognized Expert Moderator Specialist
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
Fuugie
32 New Member
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
2,851 Recognized Expert Moderator Specialist
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
Glenton
391 Recognized Expert Contributor
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

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

Similar topics

46
4172
by: Scott Chapman | last post by:
There seems to be an inconsistency here: Python 2.3.2 (#1, Oct 3 2003, 19:04:58) on linux2 >>> 1 == True True >>> 3 == True False >>> if 1: print "true" ....
3
2040
by: Jimmy Johns | last post by:
Hi, why hasn't there a version of pyOpenGL for python 2.3.x yet? Currently the binary installers for windows only work with python 2.2, and will give an when installing for python 2.3. I can't...
7
5353
by: Shawn Milo | last post by:
Is anyone doing this? I would like to access a DB2 database (IBM's database) with Python. I checked "Python in a Nutshell," and it refers to ftp://people.linuxkorea.co.kr/pub/db2, but I am unable...
3
2587
by: devendra_k | last post by:
I want to intigrate the PyGame module with my Python exe, means i DONT want to generate .PYD files separtely rather than that want to put PyGame "c" src with Python workspace of VC project...
4
2725
by: christopher diggins | last post by:
Welcome to the first installment of the Diggins Public Domain Posts (PDP). There is a significant dearth of good public domain C++ code. All of it seems to come with one kind of a license or...
53
4293
by: Michael Tobis | last post by:
Someone asked me to write a brief essay regarding the value-add proposition for Python in the Fortran community. Slightly modified to remove a few climatology-related specifics, here it is. I...
0
1060
by: edcdave | last post by:
My (gcc 2.95.2) build of Python 2.4.3 is failing with: gcc -Wl,-Bexport -o python \ Modules/ccpython.o \ libpython2.4.a -lnsl -ldl -lm Undefined first referenced...
19
11274
by: citronelu | last post by:
Is it possible to execute a binary string stored within a python script as executable code ? The script is run under Windows, and the binary code (a full executable file) is stored in a variable...
4
5123
by: 7stud | last post by:
Hi, I'm using an intel imac which came with python 2.3.5 pre-intstalled on OS 10.4.7. I was able run a hello world wxPython script in Terminal by typing: $pythonw wxPythonTest.py ...
0
7371
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7432
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
7093
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
5676
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5077
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4743
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3218
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
791
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
452
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.