Sunday, November 11, 2012

Converting a regular string to binary string in Python

Python doesn't seem to have a built-in way of converting an arbitrary string into a binary string representation.

Here's a Python function I've written for that purpose:

def str2bin(msg):
    return ''.join(bin(int(i.encode("hex"), 16))[2:] for i in msg)

There's probably a better way but this works for me.

The function makes us of a generator expression to encode each individual character in the original string into it's hexadecimal representation and using bin to turn that into a binary string. The leading 0b is stripped off before they're all combined back together into a single string again.

Useful if you want a long string of bits to play with.


No comments:

Post a Comment