String to Bits

Gribouillis 0 Tallied Votes 2K Views Share

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:]

Dani AI

Generated

As @Gribouillis has shown, there are several valid ways to turn text or bytes into a "010101..." bit string. Which to pick depends on: whether you start with a Python 3 bytes or a str (encode text first), whether you need a fixed-width output that preserves leading zeros, memory limits (whole-buffer vs streaming), and whether you want a human-readable implementation or a compact/fast one.

A clear, Python‑3-friendly pattern is to format each byte as eight bits and join them. It is readable, portable, and easy to stream for large inputs:

def bytes_to_bits(b):
    # b must be a bytes-like object; for text use s.encode('utf-8') first
    return ''.join('{:08b}'.format(byte) for byte in b)

# Example: bits = bytes_to_bits(s.encode('utf-8'))

Notes and caveats:

  • If you need a single int conversion, use int.from_bytes(b, byteorder='big') and then format; remember to pad with .zfill(len(b)*8) so leading zeros are not lost. Choose byteorder deliberately.
  • For Unicode text: encoding (UTF-8, UTF-16, etc.) determines the byte stream. If you want Unicode code points instead of encoded bytes, convert with ord() per character and choose a fixed width.
  • For very large inputs avoid building one giant string — either stream chunks to output or use a bit-level container (compact libraries exist) to save memory.

This keeps intent clear, works reliably across modern Python versions, and makes the tradeoffs explicit for different use cases.

Gribouillis 1,391 Programming Explorer Team Colleague

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 1,391 Programming Explorer Team Colleague

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

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

The

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.