How to Convert a string into binary

Jesse Hager wrffruntre at tznvy.pbz.ROT13
Sat Apr 15 22:14:02 EDT 2006


The short version:

def str2bin(s):
    return ''.join([''.join(['10'[not (m&ord(x))] for m in
       (128,64,32,16,8,4,2,1)]) for x in s])

Notes:

Split into 3 lines for newsgroup post, 3rd line is actually the end of 
the 2nd. It will run as shown above.

Returns digits in MSB order, to return LSB first, reverse the order of 
the bit weights. (1,2,4,8,16,32,64,128)

To support 16-bit Unicode, add powers of two to the bit weights up to 32768.

To put a separator between digits for each character put it between 
first set of empty quote chars. ',' -> '00000000,11111111'

To put a separator between digits of the same character, put it between 
the second set of empty quotes. '.' -> '0.1.0.1.0.1.0.1'

This is probably slower than one based on lookup tables like the others 
are proposing.

--
Jesse Hager
email = "wrffruntre at tznvy.pbz".decode("rot13")



More information about the Python-list mailing list