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.
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.
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))
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.). - jfsbytes_from_bits('0101011100100101')
returns 'W%'
, and I wanted 'здесь желаемый результат'
instead” - jfs