[Tutor] Binary math?

Jeffrey Thomas Peery jeffpeery at yahoo.com
Tue Oct 26 05:49:57 CEST 2004


Thanks for the help. Well I am aware of how computers use binary and such,
although I have to do a little arithmetic with binary numbers, I am an
engineer and I have some test data that is in hexadecimal and I need to
convert that to binary and that to regular base ten numbers. I was hoping
that there was a python module or commands that would do the binary
addition/subtraction multiplication and such. I wrote a program that seems
to work ok for what I need but I used a lot of code to do it, I was hoping
for something easier to read. If you have any thoughts please let me know.
Thanks.

J

-----Original Message-----
From: Danny Yoo [mailto:dyoo at hkn.eecs.berkeley.edu] 
Sent: Monday, October 25, 2004 11:01 AM
To: Jeff Peery
Cc: tutor at python.org
Subject: Re: [Tutor] Binary math?



On Mon, 25 Oct 2004, Jeff Peery wrote:

> will python work with binary math?

Hi Jeff,

Just to clarify: most computers work on the principle of binary.  There's
a layer of abstraction that hides the bit-twiddling from us.  When we say
something like 42, the computer is using a bit pattern to represent the
number 42:

    42   <====>  101010

                (2**5 + 2**3 + 2**1)

Python (and most computer systems) will do work using the bit-patterns,
and a separate program converts those bit-patterns back into a decimal
representation that's comfortable for humans.



> i.e., add subtract binary numbers? is there a specific type that I have
> to use to define a binary number? thanks.

What are you trying to do?  If you're trying to understand how binary math
works, I'd recommend looking at "Code":

    http://www.charlespetzold.com/code/index.html


And if you have a string with the proper bit pattern, then you can use the
int() builtin:

###
>>> int('101010', 2)
42
###


But I have to admit: I'm still a little confused at what you're asking.
Please tell us more why you're trying to do binary arithmetic, so we can
give better help.

Good luck to you!



More information about the Tutor mailing list