Home > Software engineering >  Reading binary file but want to convert to text/string
Reading binary file but want to convert to text/string

Time:08-10

I am reading a binary file:

    file = open("TPSDisplay/Reader/radio_log.BIN","rb")
    lines = file.read(100)
    file.close()

When I run print(lines), it prints the converted binary string, in this case it is:

'\r\n01659963148.977->>(\x00\x00\x00\xa5v\xe6A\x0033\x0033\x00\x00\x00\x00\x00\x00\xd9\xfb\x00\x0c\x17\x90\x01M\x04\x00\x00\x00\x1d\xb3\x1c\xf6\x8ep\xf7N\xf6\x00\x00\r\n01659963148.977->>(\x00\x00\x00\xa5v\xe6A\x0033\x0033\x00\x00\x00'

Now I want to split this string about the \r's and do general string manipulation, but since lines is not a normal string object I cannot do so.

Note: I think the hex represents an excel table as that is what is usually outputted with this binary file, if you have an idea on how to interpret the data following the long digit that would be extremely helpful as well.

CodePudding user response:

In your case, you could use

lines.decode("utf-8")

to convert the bytes to string and process it.

But binary file can not be converted to normal string that people could read.

CodePudding user response:

You can write lines.decode(someEncoding) where someEncoding is Windows/DOS codepage number as str or unicode (depending on your Python version). You can use any codepage you want.

  • Related