binary to decimal conversion
Joshua Macy
amused at webamused.com
Sun Mar 19 12:02:34 EST 2000
Bob Boyken wrote:
>
>
> 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:
>>> 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:
>>> 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.
>>> 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
More information about the Python-list
mailing list