Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>For ASCII characters in the range <code>[ -~]</code> on Python 2:</p> <pre><code>&gt;&gt;&gt; import binascii &gt;&gt;&gt; bin(int(binascii.hexlify('hello'), 16)) '0b110100001100101011011000110110001101111' </code></pre> <p>In reverse:</p> <pre><code>&gt;&gt;&gt; n = int('0b110100001100101011011000110110001101111', 2) &gt;&gt;&gt; binascii.unhexlify('%x' % n) 'hello' </code></pre> <hr> <p>In Python 3.2+:</p> <pre><code>&gt;&gt;&gt; bin(int.from_bytes('hello'.encode(), 'big')) '0b110100001100101011011000110110001101111' </code></pre> <p>In reverse:</p> <pre><code>&gt;&gt;&gt; n = int('0b110100001100101011011000110110001101111', 2) &gt;&gt;&gt; n.to_bytes((n.bit_length() + 7) // 8, 'big').decode() 'hello' </code></pre> <hr> <h3>To support all Unicode characters in Python 3:</h3> <pre><code>def text_to_bits(text, encoding='utf-8', errors='surrogatepass'): bits = bin(int.from_bytes(text.encode(encoding, errors), 'big'))[2:] return bits.zfill(8 * ((len(bits) + 7) // 8)) def text_from_bits(bits, encoding='utf-8', errors='surrogatepass'): n = int(bits, 2) return n.to_bytes((n.bit_length() + 7) // 8, 'big').decode(encoding, errors) or '\0' </code></pre> <h3>Here's single-source Python 2/3 compatible version:</h3> <pre><code>import binascii def text_to_bits(text, encoding='utf-8', errors='surrogatepass'): bits = bin(int(binascii.hexlify(text.encode(encoding, errors)), 16))[2:] return bits.zfill(8 * ((len(bits) + 7) // 8)) def text_from_bits(bits, encoding='utf-8', errors='surrogatepass'): n = int(bits, 2) return int2bytes(n).decode(encoding, errors) def int2bytes(i): hex_string = '%x' % i n = len(hex_string) return binascii.unhexlify(hex_string.zfill(n + (n &amp; 1))) </code></pre> <h3>Example</h3> <pre><code>&gt;&gt;&gt; text_to_bits('hello') '0110100001100101011011000110110001101111' &gt;&gt;&gt; text_from_bits('110100001100101011011000110110001101111') == u'hello' True </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload