954,525 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

String to Bits

0
By Gribouillis on Sep 7th, 2009 6:30 am

This snippet defines a function a2bits which converts a characters string to a string of 0's and 1's showing its bitwise representation.

import sys
if sys.version_info[0] >= 3:
    bin = "{0:#0b}".format
    from functools import reduce

def a2bits(chars):
    "Convert a string to its bits representation as a string of 0's and 1's"
    return bin(reduce(lambda x, y : (x<<8)+y, (ord(c) for c in chars), 1))[3:]

Here is a much faster version using binascii.hexlify:

from binascii import hexlify

def a2bits(bytes):
    """Convert a sequence of bytes to its bits representation as a string of 0's and 1's
    This function needs python >= 2.6"""
    return bin(int(b"1" + hexlify(bytes), 16))[3:]
Gribouillis
Posting Maven
Moderator
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691
 

Another possibility is to use a specialized module to handle binary data. One such module is bitstring ( http://pypi.python.org/pypi/bitstring/2.1.0 ). Install it with easy_install or pip. Example:

>>> from bitstring import BitString
>>> bs = BitString(bytes="hello world")
>>> bs
BitStream('0x68656c6c6f20776f726c64')
>>> bs.bin
'0b0110100001100101011011000110110001101111001000000111011101101111011100100110110001100100'

The user manual is here .

Gribouillis
Posting Maven
Moderator
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: