Search code examples
parsingjuliabinaryfiles

Parse array of unsigned integers in Julia 1.x.x


I am trying to open a binary file that I have some knowledge of its internal structure, and reinterpret it correctly in Julia. Let us say that I can load it already via:

arx=open("../axonbinaryfile.abf", "r")  
databin=read(arx)  
close(arx)

The data is loaded as an Array of UInt8, which I guess are bytes. In the first 4 I can perform a simple Char conversion and it works:

head=databin[1:4]
map(Char, head)

4-element Array{Char,1}:
 'A'
 'B'
 'F'
 ' '

Then it happens to be that in the positions 13-16 is an integer of 32 bytes waiting to be interpreted. How should I do that? I have tried reinterpret() and Int32 as function, but to no avail.


Solution

  • You can use reinterpret(Int32, databin[13:16])[1]. The last [1] is needed, because reinterpret returns you a view.

    Now note that read supports type passing. So if you first read 12 bytes of data from your file e.g. like this read(arx, 12) and then run read(arx, Int32) you will get the desired number without having to do any conversions or vector allocation.

    Finally observe that what conversion to Char does in your code is converting a Unicode number to a character. I am not sure if this is exactly what you want (maybe it is). For example if the first byte read in has value 200 you will get:

    julia> Char(200)
    'È': Unicode U+00c8 (category Lu: Letter, uppercase)
    

    EDIT one more comment is that when you do a conversion to Int32 of 4 bytes you should be sure to check if it should be encoded as big-endian or little-endian (see ENDIAN_BOM constant and ntoh, hton, ltoh, htol functions)