I do archiver. The archiving process creates a string with a binary code. I need to translate this string into bytes and write them to a file. Then I need to get these bytes from the file and translate them into a string back, without data loss
I translate into bytes and write to a file like this: `
f = open("n.bin", "wb") data = "1100101101" f.write(int(data, 2).to_bytes((len(data.lstrip('0')) + 7) // 8, 'big'))` I'm trying to get them from the file like this:
f = open("n.bin", "rb") 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' print(f.read()) print(text_from_bits(f.read())) I found the function text_from_bits on the Internet, but it does not work (like decode ()), it displays the error:
File "test_dearchive.py", line 4, in text_from_bits n = int(bits, 2) ValueError: invalid literal for int() with base 2: b'' As I understand it, the translation into bytes in the first script is correct. And how correctly to take these bytes from n.bin and translate them into the same string that was originally in data?
readmethod, you have already moved to the end of the file; a repeated call returns an empty byte sequence. 2. Inbits, you will have bytes, not a string with a binary representation of the data. - mkkik 1:23 pm