[Tutor] binary data as string?

Alan Gauld alan.gauld at blueyonder.co.uk
Fri Apr 16 14:09:50 EDT 2004


> > mask = 1
> > data = 42
> > for n in range(8):
> >    print (data & mask) and 1 or 0,
> >    mask = mask << 1
> 
> s/<</>>/
>  
> > Will print out the bit pattern of 42...

Actually no, that'll drop the 1 off the end and 
only print the first bit accurately.

However mine wasn't much better since it prints 
the bits in reverse order!

Lets fix both errors:

mask = 128    # = 1000000
data = 42
for n in range(8):
    print (data & mask) and 1 or 0,
    mask = mask >> 1

Should do it properly...

:-)

Alan G.




More information about the Tutor mailing list