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?

  • 1. After the first call to the read method, you have already moved to the end of the file; a repeated call returns an empty byte sequence. 2. In bits , you will have bytes, not a string with a binary representation of the data. - mkkik 1:23 pm
  • 1. yes, indeed, f.read () changes the behavior, removed this function. 2. and how then is it better to do differently? - Gosh Usual

1 answer 1

Use the reverse from_bytes method:

 with open('n.bin', 'rb') as f: print(bin(int.from_bytes(f.read(), 'big'))) # -> 0b1100101101