On Aug 9, 11:18 pm, azrael <[EMAIL PROTECTED]> wrote: > Hy folks, > > I googled, and searched, and can not bealive that I have not found a > built in way to convert the easy and elegant python way a function to > easily convert simple ascii data to binary and back. > > I've written some my own but they were pretty slow using binascii > linbrary with hexifly and unhexifly functions conbined with a > lookuptable of binary and hex values. > > Any idea how to easily write a function that recieves a character or > string and returns a binary number like: > ascii("1") is converted to bin("00110001")
Here's one way: >>> def a2b(a): ... ai = ord(a) ... return ''.join('01'[(ai >> x) & 1] for x in xrange(7, -1, -1)) ... >>> a2b('1') '00110001' >>> a2b('2') '00110010' >>> a2b(chr(0)) '00000000' >>> a2b(chr(255)) '11111111' >>> BUT ... why are you doing this so much that the speed matters??? -- http://mail.python.org/mailman/listinfo/python-list