-2

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.

Carl M
  • 215
  • 3
  • 10
  • 1
    This question appears to be off-topic because this isn't a code translation service – jonrsharpe Oct 03 '14 at 21:17
  • @jonrsharpe - Not looking for a translation if unwilling to provide one. Any help/hint/pointed finger in the right direction is greatly appreciated. – Carl M Oct 03 '14 at 21:26
  • 1. Learn some IDL. 2. Figure out what that code does. 3. Learn some Python. 4. Write the same code in Python. Presumably you're here because that sounds like too much work, so... maybe try RentACoder? – jonrsharpe Oct 04 '14 at 07:19
  • 1
    You come across as incredibly rude. Thanks for the advice. – Carl M Oct 04 '14 at 09:42

1 Answers1

1

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.

T.Woody
  • 1,142
  • 2
  • 11
  • 25