Group Abstract Group Abstract

Message Boards Message Boards

Import binary data from a file

Hi all,
I have a large file with data that was created by a Python script. The format of each line is like b'\x01\x00\fd' (my lines are much longer).
I know that these lines represent a set of bytes represented as a string using a kind of encoding (very common in Python).
My problem is how to import this data to a Mathematica notebook.
I can import the strings. The problem is how to decode the data in between b' and ' and extract the values of the each byte.

POSTED BY: Adriano Moreira

This works for me:

importPythonBytes[str_String]:=ToCharacterCode @ 
    StringReplace[str, {
         "\\x"~~hex:(HexadecimalCharacter..) :> 
        FromCharacterCode[FromDigits[hex,16]],"\\f"->"\f"
   }
];    
importPythonBytes["\\x01\\x00\\fd"]
(* \[RightArrow]{1,0,12,100}*)
POSTED BY: Rolf Mertig
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard