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

前端 未结 2 970
天涯浪人
天涯浪人 2021-01-05 02:38

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 chara

相关标签:
2条回答
  • 2021-01-05 03:04

    to get the 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:

    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
    
    0 讨论(0)
  • 2021-01-05 03:16

    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 ?

    0 讨论(0)
提交回复
热议问题