binary to decimal conversion
Author Message binary to decimal conversion

This morning I wrote a function that takes a binary number as a string
and converts it to an integer. There must be a way to optimize this
function, anyone have some tips?

def btoi(num):
output = 0
col = range(len(num))
col.reverse()
for bit in range(len(num)):
output = output + pow(2,col[bit])*int(num[bit])
return output

Thanks,
Michael
_______________________________________________________________

Wed, 04 Sep 2002 03:00:00 GMT  binary to decimal conversion

Quote:

> This morning I wrote a function that takes a binary number as a string
> and converts it to an integer. There must be a way to optimize this
> function, anyone have some tips?

> def btoi(num):
>     output = 0
>     col = range(len(num))
>     col.reverse()
>     for bit in range(len(num)):
>         output = output + pow(2,col[bit])*int(num[bit])
>     return output

> Thanks,
> Michael
> _______________________________________________________________

Yes, use string.atoi

>>> import string
>>> string.atoi("110", 2)
6
>>> string.atoi("110110", 2)
54

Joshua

Wed, 04 Sep 2002 03:00:00 GMT  binary to decimal conversion

Quote:

>> This morning I wrote a function that takes a binary number as a string
>> and converts it to an integer. There must be a way to optimize this
>> function, anyone have some tips?

>> def btoi(num):
>>     output = 0
>>     col = range(len(num))
>>     col.reverse()
>>     for bit in range(len(num)):
>>         output = output + pow(2,col[bit])*int(num[bit])
>>     return output

>> Thanks,
>> Michael
>> _______________________________________________________________

>   Yes, use string.atoi

>  >>> import string
>  >>> string.atoi("110", 2)
>  6
>  >>> string.atoi("110110", 2)
>  54

Is there an equivalent function to turn an integer into a binary string?  One that
would give me "110110" if I fed it "54"?  While I'm at it, I also seek a function
that will count the bits in a binary string.  If these sound like stupid questions,
cut me some slack-- I've only been programming in python for 3 days...

Thanks,

Bob

- Show quoted text -

Quote:

>   Joshua

Wed, 04 Sep 2002 03:00:00 GMT  binary to decimal conversion

Quote:
> This morning I wrote a function that takes a binary number as a string
> and converts it to an integer. There must be a way to optimize this
> function, anyone have some tips?

> def btoi(num):
>     output = 0
>     col = range(len(num))
>     col.reverse()

current_power = 1
Quote:
>     for bit in range(len(num)):
>         output = output + pow(2,col[bit])*int(num[bit])

Better:
if num[bit] == '1':
output = output+current_power
current_power = current_power << 1

Or try some list functions:

powers = map(pow, *len(num), range(len(num)))
return reduce(operator.add, map(operator.mult, powers, map(int, num)))

(You can calculate powers in advance, and just take slices)
--

http://www.oreilly.com/news/prescod_0300.html
http://www.linux.org.il -- we put the penguin in .com

Thu, 05 Sep 2002 03:00:00 GMT  binary to decimal conversion
I would do the following:

def btoi(num):
output = 0
for bit in range(len(num)):
output = output << 1
if num[bit] == '1':
output = output + 1
return output

That lets you get rid of the call to reverse(), and all the extra
variables.

|
| > This morning I wrote a function that takes a binary number as a string
| > and converts it to an integer. There must be a way to optimize this
| > function, anyone have some tips?
| >
| > def btoi(num):
| >     output = 0
| >     col = range(len(num))
| >     col.reverse()
|       current_power = 1
| >     for bit in range(len(num)):
| >         output = output + pow(2,col[bit])*int(num[bit])
| Better:
|           if num[bit] == '1':
|               output = output+current_power
|           current_power = current_power << 1
|
| Or try some list functions:
|
| powers = map(pow, *len(num), range(len(num)))
| return reduce(operator.add, map(operator.mult, powers, map(int, num)))
|
| (You can calculate powers in advance, and just take slices)
| --

| http://www.oreilly.com/news/prescod_0300.html
| http://www.linux.org.il -- we put the penguin in .com
|
|

--
cliff crawford    -><-    http://www.people.cornell.edu/pages/cjc26/
"IS I yes wardrobe yield [the] evaluation."     member of A.H.M.A.D.

Thu, 05 Sep 2002 03:00:00 GMT  binary to decimal conversion

Quote:

> Is there an equivalent function to turn an integer into a binary string?  One that
> would give me "110110" if I fed it "54"?  While I'm at it, I also seek a function
> that will count the bits in a binary string.  If these sound like stupid questions,
> cut me some slack-- I've only been programming in Python for 3 days...

I don't know of a builtin function to produce the binary string given
the number, although both hex and octal have at least two ways to do it:

Quote:
>>> import string
>>> a = string.atoi("110110", 2)
>>> print a, hex(a), oct(a)
54 0x36 066
>>> print "%d %x %o" % (a, a, a)
54 36 66

I would probably write a binary string representation function by doing
substitution on the nibbles of the octal representation, but that may
not be the best or most efficient way:

import string

class DecimalToBinary:
"""DecimalToBinary takes a decimal string and produces a binary
representation of it"""
nibble = { '0' : '000',
'1' : '001',
'2' : '010',
'3' : '011',
'4' : '100',
'5' : '101',
'6' : '110',
'7' : '111' }
def __init__(self, newStr=None):
if newStr:
self.decimal = string.atoi(newStr)
else:
self.decimal = 0

def setDecimal(self, newStr):
self.__init__(newStr)

def __repr__(self):
import string
ret = ""
octal = oct(self.decimal)[1:] # ignore leading 0 of octal format
for char in octal:
ret = ret + DecimalToBinary.nibble[char]
return ret

Then:

Quote:
>>> b = DecimalToBinary("54")
>>> print b
110110
>>> b.setDecimal("7")
>>> print b
111

As I said, probably not the most efficient, but it has the advantage of
being the first thing that occurred to me.

As for counting the bits in the binary string, I'm not sure whether you
mean counting the number of 1's or the number of positions.

Quote:
>>> a = "110110"
>>> print "Length = ", len(a)
Length =  6
>>> print "Ones = ", string.count(a, "1")
Ones =  4

One of the things I like best about the python newsgroup is that an
almost infinite amount of slack is here for the asking (as long as you
avoid certain topics like "Why does this stupid language use whitespace
as a delimiter?")

Joshua

Thu, 05 Sep 2002 03:00:00 GMT  binary to decimal conversion
Okay, here my decimal to string representing binary value. I
append a lowercase b to the end to make it more readable (for me)
and you can get the number of bits by taking the len() - 1.

def bin(num):
"""
Returns a string binary representation of a number. For
example
bin(255) returns '11111111b'.

"""
returnValue = 'b'
i = 0
while(1):
if (i != 0) and (mask > num):
break
returnValue = '1' + returnValue
else:
returnValue = '0' + returnValue
i = i + 1

return returnValue

Cheers,

Willy

* Sent from RemarQ http://www.remarq.com The Internet's Discussion Network *
The fastest and easiest way to search and participate in Usenet - Free!

Thu, 05 Sep 2002 03:00:00 GMT  binary to decimal conversion
Out of curiosity, why is this (or any of the other {*filter*} solutions put
forth) better than:

import string
string.atoi( value, 2)

import string
string.atoi( value[:-1], 2 )

???
Mike

Quote:
-----Original Message-----

Sent: Sunday, March 19, 2000 5:41 PM

Subject: Re: binary to decimal conversion

Okay, here my decimal to string representing binary value. I
append a lowercase b to the end to make it more readable (for me)
and you can get the number of bits by taking the len() - 1.
...

Thu, 05 Sep 2002 03:00:00 GMT  binary to decimal conversion
Urgh, never mind, just realised you changed the topic without changing the
subject line, you're now working on decimal to binary, not binary to decimal
conversions...

Sorry all,
Mike

Quote:
-----Original Message-----

Sent: Sunday, March 19, 2000 7:00 PM

Subject: RE: binary to decimal conversion

... stuff clipped 'cause was irrelevant

Thu, 05 Sep 2002 03:00:00 GMT  binary to decimal conversion

Quote:
>> This morning I wrote a function that takes a binary number as a string
>> and converts it to an integer. There must be a way to optimize this
>> function, anyone have some tips?
>> [snip]
> Yes, use string.atoi
> >>> import string
> >>> string.atoi("110", 2)
> 6
> [snip]

...or in the latest CVS Python (what will become v1.6), you can use int():

Python 1.5.2+ (#0, Feb  1 2000, 13:53:38) [MSC 32 bit (Intel)] on win32
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam

Quote:
>>> int("101010", 2)

42

I-always-thought-there-was-something-fundamentally-wrong-with-the-universe-l
y
y'rs

-----------------------------------------------------------------

Fri, 06 Sep 2002 03:00:00 GMT  binary to decimal conversion

Quote:
> This morning I wrote a function that takes a binary number as a string
> and converts it to an integer. There must be a way to optimize this
> function, anyone have some tips?

> def btoi(num):
>     output = 0
>     col = range(len(num))
>     col.reverse()
>     for bit in range(len(num)):
>         output = output + pow(2,col[bit])*int(num[bit])
>     return output

# - - - - - -
def btoi(num, o="0", i="1"):
def powL(a, e): # can handle BIG numbers (long)
import sys
mi = sys.maxint # maximal value of integer. Higher must be long.
r = 1L
for i in range(e):
r = r*a
if r < mi: return int(r)
return r
c = [o, i]
output = 0
for i in range(len(num)):
output = output+c.index(num[-i-1])*powL(2, i)
# - - - - - -
Without warranty. Reproduced from my brain. (I wrote this func before
a week. This func should handle VERY large strings which yield long
numbers. If the strings conains binary string using other characters e.g.
s = "IOOOIOIOIOOOIOI", you simply use: btoi(s, "O", "I")

regards,
Michal Bozon
Fac.Sci., Chrales Univ., Prague, Czech Rep.

Quote:

> Thanks,
> Michael
> _______________________________________________________________

Sat, 07 Sep 2002 03:00:00 GMT  binary to decimal conversion
what's wrong with

i = string.atoi(s, 2)

?
if you want to roll your own for some reason, this works:

def atobin(str):
v = 0L
for c in s:
v = v << 1
if c == '1': v = v + 1
return v

If the result is negative you overflowed.

You can find out how many binary digits an integer will use with this
function:

def binarydigits(n):
if n = 0:
return 1
else:
return 1 + int(math.log(abs(n)) / math.log(2))

(negative numbers are usually represented with a sign bit, but that's a

On my system (Windows 2000), binarydigits(sys.maxint) returns 31.

Greg Jorgensen

Sat, 07 Sep 2002 03:00:00 GMT  binary to decimal conversion

Quote:

> def btoi(num, o="0", i="1"):
>     def powL(a, e): # can handle BIG numbers (long)
>        ...
>     c = [o, i]
>     output = 0
>     for i in range(len(num)):
>         output = output+c.index(num[-i-1])*powL(2, i)

Calculating 2^n from scratch for each bit is a tad wasteful.

def btoi(num):
result = 0L
bit = 1L
n = len(num)
while n:
n = n - 1
if num[n] == "1":
result = result + bit
bit = bit << 1
if result <= sys.maxint:
return int(result)
else:
return result

--
Greg Ewing, Computer Science Dept,
+--------------------------------------+
University of Canterbury,          | A citizen of NewZealandCorp, a       |
Christchurch, New Zealand          | wholly-owned subsidiary of USA Inc.  |

Sun, 08 Sep 2002 03:00:00 GMT  binary to decimal conversion

I write three functions:
import string

#-------------------------------
__doc__ = 'Data convert function.   written by ezra.\012'

def Int2Bin(di):
chars = ['0','1']
do = ''
q = 0
while di >= 2:
q = di % 2
do = chars[q] + do
di = di / 2
do = chars[di] + do
if len(do)%4 >= 1 and len(do)%4 <= 3 : do = '0'*(4 - len(do)%4) + do
return do
# End of def Int2Bin(di)

def Int2Oct(di):
chars = ['0','1','2','3','4','5','6','7']
do = ''
q = 0
while di >= 8:
q = di % 8
do = chars[q] + do
di = di / 8
do = chars[di] + do
if len(do)%2 == 1 : do = '0' + do
return do
# End of def Int2Oct(di)

def Int2Hex(di):
chars =
['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']
do = ''
q = 0
while di >= 16:
q = di % 16
do = chars[q] + do
di = di / 16
do = chars[di] + do
if len(do)%2 == 1 : do = '0' + do
return do
# End of def Int2Hex(di)

#-------------------------------

--
(Wei-Neng Hung)
,
High-Speed Communication and Computing Laboratory,NCU

Fri, 13 Sep 2002 03:00:00 GMT

 Page 1 of 2 [ 15 post ]

Relevant Pages