Hello. I convert str to blob / hex / binary using the function:

def strbin(s): return ''.join(format(ord(i),'0>8b') for i in s) 

Prompt a function that would act the opposite (mirror) of this.

1 answer 1

To convert the "01" string of bits to the corresponding byte string:

 import binascii def bytes_from_bits(bits): """'0101011100100101' -> b'W%'""" return int2bytes(int(bits, 2)) def int2bytes(i): """22309 -> b'W%'""" hex_string = '%x' % i n = len(hex_string) return binascii.unhexlify(hex_string.zfill(n + (n & 1))) 

To convert bytes to the corresponding bit string (ascii string representing a binary number):

 def bytes_to_bits(bytestring): """b'W%' -> '0101011100100101'""" bits = bin(int(binascii.hexlify(bytestring), 16))[2:] return bits.zfill(8 * ((len(bits) + 7) // 8)) 
  • When decoding, 2 line breaks appear in place 1 (in the source text) - LorDo
  • @LorDo: you probably on Windows where line breaks are two bytes: b'\r\n' . If you think that some function does not work, then specify which function (there are 3 of them in the answer) and give a minimal example: what is the input (in the form of a string constant such as '10001111' ) that the function returns (do not use words to describe and show the result such as: '\x8f' ), and what you want to get instead (again in the form of repr(result) ). If you are trying to convert a text file to bits and back, then this is a separate question (encoding, '\n' <-> os.linesep etc.). - jfs
  • I am trying to convert to bits and back a long string in which there are line breaks (\ r and \ n). Here is the fitting "line": pastebin.com/zniCPrSy . I translate it into bits using my function in the question header (strbin). And I get the pastebin.com/jsfmExMj code. Next, I try to convert the first 2 functions from your post back to text (more precisely, bytes_from_bits) and get the output of pastebin.com/tBjGEpi8 . As you can see with the transfer of the line something is not right. - LorDo
  • no need to paste on pastebin. I asked for a minimal example such as: bytes_from_bits('0101011100100101') returns 'W%' , and I wanted 'здесь желаемый результат' instead” - jfs
  • Yes, God knows how to bring a minimal example here so that it would be clear, I already laid it out on Pastenbin, there is clearly a problem with line breaks. - LorDo