Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read in 4-byte words from binary file in Julia

I have a simple binary file that contains 32-bit floats adjacent to each other.

Using Julia, I would like to read each number (i.e. each 32-bit word) and put them each sequentially into a array of Float32 format.

I've tried a few different things through looking at the documentation, but all have yielded impossible values (I am using a binary file with known values as dummy input). It appears that:

  1. Julia is reading the binary file one-byte at a time.

  2. Julia is putting each byte into a Uint8 array.

For example, readbytes(f, 4) gives a 4-element array of unsigned 8-bit integers. read(f, Float32, DIM) also gives strange values.

Anyone have any idea how I should proceed?

like image 949
William Avatar asked Aug 11 '14 21:08

William


1 Answers

I'm not sure of the best way of reading it in as Float32 directly, but given an array of 4*n Uint8s, I'd turn it into an array of n Float32s using reinterpret (doc link):

raw = rand(Uint8, 4*10)  # i.e. a vector of Uint8 aka bytes
floats = reinterpret(Float32, raw)  # now a vector of 10 Float32s

With output:

julia> raw = rand(Uint8, 4*2)
8-element Array{Uint8,1}:
 0xc8
 0xa3
 0xac
 0x12
 0xcd
 0xa2
 0xd3
 0x51

julia> floats = reinterpret(Float32, raw)
2-element Array{Float32,1}:
 1.08951e-27
 1.13621e11
like image 142
IainDunning Avatar answered Sep 27 '22 17:09

IainDunning