0

I'm trying to make a simple compressor (I think the algorithm is done) but when trying to get read the bytes from a file and converting them to binary i'm not able to do it.

I have a BitArray that should be referring to a file 'test.png'

b = BitArray(bytes=open('test.png', 'rb').read())

And when I print b I get:

0x89504e470d0a1a0a0000000d494844520000031000000369080200000014b648a3000000017352474200aece1ce90000000467414d410000b18f0bfc6105000000097048597300000ec300000ec301c76fa86400008e9149444154785eeddd07781445e3c771ae25744215044445b0e3abd81b8205ebabd87dedbdf7de...

I'm trying to get the binary value as following:

b = bin(int(str(b), 16))
print(b)

But I get the following error:

ValueError: invalid literal for int() with base 16

I'm wondering if this is because the number is very large?

Thanks in advance!

2
  • 1
    Have you ever considered using bytearray? It's the built in type for working with binary data (i.e. files). Reading file will look somewhat like this: bytes = bytearray(open('test.png', 'rb').read()); writing: open('test.png', 'rb').write(bytes). It's also considrerd a good practice to either close() files after you've opened them or use them withing a context manager (e.g. with open('test.png', 'rb') as file:). Hope that helps! Commented Dec 13, 2022 at 1:50
  • Thank you so much! I used bytearray and after that binary = bin(int.from_bytes(bytes, byteorder=sys.byteorder)) and it worked! Commented Dec 13, 2022 at 2:11

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.