0

I'm trying to get a binary representation of a music (.mp) file in python. I'm currently only capable to get it represented in bytes. When I try to convert those bytes to binary, I keep getting errors. This is my current program:

folder=os.listdir(os.getcwd())
for files in folder:
    if files.endswith(".mp3"):
        file = open(files, 'rb')
        stream = str(file.read()).split("\\")
        print(stream)
        for bit in range(1,len(stream)):
            """
            print(stream[bit])
            newbit = f"0{stream[bit]}"
            c = BitArray(hex=newbit)
            #print(c.bin)
            """
            print(stream[bit][1:])
            print(bin(int(stream[bit][1:], base=16)))

I keep getting the same error:

line 39, in <module>
print(bin(int(stream[bit][1:], base=16)))
ValueError: invalid literal for int() with base 16: '00Info'

When I go and check the bytes from the statement print(stream) the byte x00Info doesn't show up. I've never worked with bytes before so I have no idea what's going on.

Seppukki
  • 563
  • 2
  • 8
  • 24
  • 1
    (1) You shouldn't convert the bytes to string with "str" if you want to work with the bytes later. (2) The "int" type has a method "from_bytes" to create an int from bytes (if this is really what you want) – Michael Butscher Jul 07 '20 at 19:37
  • What exactly are you trying to do? You want zeros and ones? – Brad Jul 08 '20 at 01:41
  • Michael Butscher: Yeah, that's prob right. But I was just really confused that there was a bit ´00Info´. That left me surprised. And Brad: yes I want 0's and 1's – Seppukki Jul 08 '20 at 08:30

1 Answers1

1
import sys
with open(sys.argv[1], 'rb') as f:
    for c in f.read():
        print(bin(c)[2:])

You don't specify what you're expecting as output, but, this will print the binary.

Macattack
  • 1,917
  • 10
  • 15
  • Thanks, that's way simpler than I imagined. Is there any way to reverse the binary stream back to a .mp3 file? I'm trying to write an LSB encoding/encryption. – Seppukki Jul 08 '20 at 08:31
  • Probably something like this: https://stackoverflow.com/questions/32675679/convert-binary-string-to-bytearray-in-python-3 – Macattack Jul 08 '20 at 20:34
  • Keep in mind what i posted above doesn't 0 prefix anything which may be a problem you'll need to solve. @Seppukki – Macattack Jul 08 '20 at 20:34
  • Thanks for the hint but I already solved it. Just created a `while` loop that checks the lenght of the string and adds a zero to the beginning until the length reaches 8 – Seppukki Jul 09 '20 at 08:34