Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You're looking for this:</p> <pre><code>packed_data = ''.join(chr(int(asciiString[i:i+8], 2)) for i in range(0, len(asciiString), 8)) </code></pre> <p>It will take 8 bits at a time from the <code>asciiString</code>, interpret it as an integer, and output the corresponding byte.</p> <p>Your problem here is that this requires the length of <code>asciiString</code> to be a multiple of 8 bits to work correctly. If not, you'll insert zero bits before the last few real bits.</p> <p>So you need to store the number of bits in the last byte somewhere, so you know to ignore those bits when you get them back, instead of interpreting them as zeros. You could try:</p> <pre><code>packed_data = chr(len(asciiString) % 8) + packed_data </code></pre> <p>Then when you read it back:</p> <pre><code>packed_input = coded_file.read() last_byte_length, packed_input, last_byte = (packed_input[0], packed_input[1:-1], packed_input[-1]) if not last_byte_length: last_byte_length = 8 ascii_input = ''.join(chain((bin(ord(byte))[2:].zfill(8) for byte in packed_input), tuple(bin(ord(last_byte))[2:].zfill(last_byte_length),))) # OR # ascii_input = ''.join(chain(('{0:0=8b}'.format(byte) for byte in packed_input), # tuple(('{0:0=' + str(last_byte_length) + '8b}').format(last_byte),))) </code></pre> <p>Edit: You either need to strip '0b' from the strings returned by <code>bin()</code> or, on 2.6 or newer, preferably use the new, alternate versions I added that use string formatting instead of <code>bin()</code>, slicing, and <code>zfill()</code>.</p> <p>Edit: Thanks eryksun, good to use chain to avoid making a copy of the ASCII string. Also, need to call <code>ord(byte)</code> in the <code>bin()</code> version.</p>
 

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