I want to convert a binary string into ASCII. The string contains 588 token {0, 1}. I've tried it with binascii: https://docs.python.org/3/library/binascii.html Or like this: Convert binary to ASCII and vice versa
Sample-Code:
sentence ="0b0101010101..."
n = int(sentence, 2)
print (n.to_bytes((n.bit_length() + 7) // 8, 'big').decode())
Output:
Error: print (n.to_bytes((n.bit_length() + 7) // 8, 'big').decode())
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x87 in position 1: invalid start byte
Edit: this is now my solution any ideas to optimize the code?
sentence ="0b0101010101..."
length=(int(len(sentence)/8)*8)+2
n = int(sentence[:length:1], 2)
print (n.to_bytes((n.bit_length() + 7) // 8, 'big').decode("utf_8", "ignore"))
SOLVED!