As a more pythonic way, you can first convert the string to a byte array, and then use the bin function in map :
>>> st = "hello world" >>> map(bin,bytearray(st)) ['0b1101000', '0b1100101', '0b1101100', '0b1101100', '0b1101111', '0b100000', '0b1110111', '0b1101111', '0b1110010', '0b1101100', '0b1100100']
Or you can join it:
>>> ' '.join(map(bin,bytearray(st))) '0b1101000 0b1100101 0b1101100 0b1101100 0b1101111 0b100000 0b1110111 0b1101111 0b1110010 0b1101100 0b1100100'
Note that in python3 you need to specify the encoding for the bytearray function:
>>> ' '.join(map(bin,bytearray(st,'utf8'))) '0b1101000 0b1100101 0b1101100 0b1101100 0b1101111 0b100000 0b1110111 0b1101111 0b1110010 0b1101100 0b1100100'
You can also use the binascii module in python 2:
>>> import binascii >>> bin(int(binascii.hexlify(st),16)) '0b110100001100101011011000110110001101111001000000111011101101111011100100110110001100100'
hexlify returns the hexadecimal representation of binary data, then you can convert to int by specifying 16 as the base, then convert it to binary with bin .
KasrΓ’mvd Jun 04 '15 at 10:58 2015-06-04 10:58
source share