translating ascii to binary

Tino Wildenhain tino at wildenhain.de
Wed Sep 17 14:34:37 EDT 2008


hi,

Canned wrote:
> Steven D'Aprano schreef:
>> Your "ascii_to_bin" method tries to do too much in one method. You should 
>> split the functionality into small, self-contained pieces, then combine 
>> them. And frankly, once you got to the part where you started popping and 
>> inserting, my brain melted. You are making an easy job too hard! *smiles*
>>
> It's a bad habit, I can't help it. From now on, I'll follow your advice
> to split the functionality into small, self-contained pieces. That
> popping and inserting is just a workaround for another workaround.

just got an interesting idea for the core of the converter,
maybe you like it:

def int_to_bin(v):
	i=1
	d=1
	a=0
	while i<v:
		if i & v:
			a+=d
		i<<=1 # could also be i*=2
		d*=10
	return a


 >>> int_to_bin(5)
101
 >>> print "%08d" % int_to_bin(5)
00000101

I think the formatting bit is a tad nicer then '0' * (8-len(...)))

Cheers
Tino
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/x-pkcs7-signature
Size: 3241 bytes
Desc: S/MIME Cryptographic Signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20080917/093ee158/attachment-0001.bin>


More information about the Python-list mailing list