Print a string in binary format

Stephen Thorne stephen.thorne at gmail.com
Thu Jan 20 21:32:48 EST 2005


On Fri, 21 Jan 2005 01:54:34 GMT, Kartic
<removethis.kartic.krishnamurthy at gmail.com> wrote:
> 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'

Death to inappropriate usage of lambda.
First of all, that lambda is buggy, it doesn't work for negative
numbers, but you can't immediately see that because of the compressed
nature of the code.

The lambda, with the bug corrected, converts to a function that looks like this.
def bstr(n, length=16):
  if n == 0: 
    return '0'
  if n<0:
      return bstr((long(2)<<length)+n) 
  return bstr(n>>1).lstrip('0') + str(n&1)

As you can see, the kwarg used is actually only used for the negative
numbers, so we can make this more concise as:
def bstr(n):
  if n == 0: 
    return '0'
  return bstr(n>>1).lstrip('0') + str(n&1)

But this isn't what we want, because we want bstr(1) to == '00000001'
not '1'. So lets just throw the POS away and rewrite it, firstly:

Test Cases:

assert bstr(0) == '00000000'
assert bstr(1) == '00000001'
assert bstr(255) == '11111111'
assert bstr(128) == '10000000'

def bstr(n): # n in range 0-255
  return ''.join([str(n >> x & 1) for x in (7,6,5,4,3,2,1,0)])

Took me a little bit, and I replaced xrange(7,-1,-1) with the much
clearer precomputed tuple, but what we have a recursionless function
that actually fulfills the requirements.

This can be used in the original poster's situation to output data in
(almost) readable binary format using something like the following:

f = file('myfile', 'rb')
while 1:
  bytes = f.read(8)
  if not bytes:
    break
  print ' '.join([bstr(ord(c)) for c in bytes])

Regards,
Stephen Thorne



More information about the Python-list mailing list