Python, how to read source binary from file? (Audio / video / text)

I want to read the source binary of a file and put it in a string. I am currently opening a file with the "rb" flag and printing the byte, but it appears as ASCII characters (for the text that is, for the video and audio files that it gives the characters and gibberish). I would like to get raw 0 and 1, if possible. This should work for audio and video files as well, so simply converting ascii to binary is not an option.

file = open(filePath, "rb") with file: byte = file.read(1) print byte 
+6
source share
2 answers

What you are reading is really the "raw binary" content of your "binary" file. Oddly enough, binary data is not "0 and 1", but binary words (aka bytes, cf http://en.wikipedia.org/wiki/Byte ) that have an integer (base 10) value and can be interpreted as ascii characters. Or as integers (as usual, binary operations). Or like hexadecimal. For what it's worth, the β€œtext” is actually β€œraw binary data”.

To get a "binary" representation, you can look here: Convert binary files to ASCII and vice versa , but it will not give you more "raw binary data" "than what you actually have ...

Now the question is: why do you want this data to be "0 and 1" for sure?

+7
source

to get a binary representation, I think you will need to import binascii, then:

 byte = f.read(1) binary_string = bin(int(binascii.hexlify(byte), 16))[2:].zfill(8) 

or, broken down by:

 import binascii filePath = "mysong.mp3" file = open(filePath, "rb") with file: byte = file.read(1) hexadecimal = binascii.hexlify(byte) decimal = int(hexadecimal, 16) binary = bin(decimal)[2:].zfill(8) print("hex: %s, decimal: %s, binary: %s" % (hexadecimal, decimal, binary)) 

will output:

 hex: 64, decimal: 100, binary: 01100100 
+6
source

Source: https://habr.com/ru/post/958149/


All Articles