Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python how to read raw binary from a file? (audio/video/text)

I want to read the raw binary of a file and put it into a string. Currently I am opening a file with the "rb" flag and printing the byte but it's coming up as ASCII characters (for text that is, for video and audio files it's giving symbols and gibberish). I'd like to get the raw 0's and 1's if possible. This needs to work for audio and video files as well so simply converting the ascii to binary isn't an option.

with open(filePath, "rb") as file:
    byte = file.read(1)
    print byte
like image 528
user2803250 Avatar asked Nov 15 '13 15:11

user2803250


People also ask

How do I read a binary file in Python?

You can open the file using open() method by passing b parameter to open it in binary mode and read the file bytes. open('filename', "rb") opens the binary file in read mode.

Are raw files binary?

A Raw Binary File contains the binary equivalent of a Tabular Text File (. ttf). You can also generate Raw Binary Files with the makeprogfile utility, or from previously generated SRAM Object Files (. sof) or Partial Mask SRAM Object Files (.


1 Answers

What you are reading IS really the "raw binary" content of your "binary" file. Strange as it might seems, binary data are not "0's and 1's" but binary words (aka bytes, cf http://en.wikipedia.org/wiki/Byte) which have an integer (base 10) value and can be interpreted as ascii chars. Or as integers (which is how one usually do binary operations). Or as hexadecimal. For what it's worth, "text" is actually "raw binary data" too.

To get a "binary" representation you can have a look here : Convert binary to ASCII and vice versa but that's not going to give you more "raw binary data" than what you actually have...

Now the question: why do you want these data as "0's and 1's" exactly ?

like image 72
bruno desthuilliers Avatar answered Oct 11 '22 20:10

bruno desthuilliers