Print a string in binary format

Kartic removethis.kartic.krishnamurthy at gmail.com
Thu Jan 20 20:54:34 EST 2005


neutrino said the following on 1/20/2005 8:21 PM:
> Mmm, the output format that I want is like:
> 0001110011111111000000001111111100000000....
> 
> I tried your code on Cygwin under Windows 2000, and on Linux, but it
> prints out ASCII characters.
> 

Aha..I guess I posted too soon.

You might want to take a look at this cookbook entry:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/219300

Defines lambdas to convert integer to binary. The one you probably want is -
 >>> bstr = lambda n, l=16: n<0 and binarystr((2L<<l)+n) or n and 
bstr(n>>1).lstrip('0')+str(n&1) or '0'
 >>> bstr(ord('a'))
'1100001'

--Kartic



More information about the Python-list mailing list