Search code examples
pythonbinaryfilesidl

Read binary file in Python using IDL function as reference


I am wanting to read a binary file using Python. I've so far used numpy.fromfile but have not been able to figure out the structure of the resultant array. I have an IDL function that would read the file, so this is the only thing I have to go on. I have no knowledge of IDL at all.

The following IDL function will read the file and return lc,zgrid,fnu,efnu etc.:

 openr,lun,'file.dat',/swap_if_big_endian,/get_lun
 s = lonarr(4) & readu,lun,s
 NFILT=s[0] & NTEMP = s[1] & NZ = s[2] & NOBJ = s[3]
 tempfilt = dblarr(NFILT,NTEMP,NZ)
 lc = dblarr(NFILT) ; central wavelengths
 zgrid = dblarr(NZ)
 fnu = dblarr(NFILT,NOBJ)
 efnu = dblarr(NFILT,NOBJ)
 readu,lun,tempfilt,lc,zgrid,fnu,efnu
 close,/all

But am unsure how to replicate this in Python. Any help is appreciated. Thanks.

I'm not looking for translation. I'm looking for a springboard from which I can try and solve this problem.


Solution

  • To read a binary file (assuming this is 32 bits or something the user already knows), I would first make a method that uses,

        >>> a = '00011111001101110000101010101010'
        >>> int(a,2)
                523700906
    

    That is, our method has to convert this from something we make ourselves, such as:

    def binaryToAscii(string_of_binary):
        '''
        binaryToAscii takes in a string of binary and returns an ASCII character
        '''
        charVal = int(string_of_binary,2)
        char    = chr(charVal)
        return char
    

    The next step would be to make a method that incorporates binaryToAscii in such a way that we are either concatenating some string, or writing to a new file. This should be left to the user to decide.

    As an aside, if you are not retrieving the binary as a string, then there our built in methods that turn unicode characters into ascii values by taking in there unicode value (binary included).

    Regarding the reading of a file, the same link for reading and writing to a file can be used.