Anthony Scemama
Anthony Scemama

Reputation: 1593

OCaml Bytes to Bigarray

I have a C program that has in memory an array of double or an array of int. The C program sends the corresponding binary data using ZeroMQ to an OCaml program. The OCaml program receives some bytes, and now I want to transform these bytes into an Array of int or an Array of float. How can I do this?

Upvotes: 1

Views: 334

Answers (1)

hcarty
hcarty

Reputation: 1671

You can use ocplib-endian to read the raw values from the string.

For example, a function to read double values from a string buffer:

let read_double buf offset =
  (* Multiply by 8 for 8-byte doubles *)
  EndianString.LE.get_double buf (offset * 8)

If you know/check/assume that the string is nothing but doubles then you can use the read_double function like this to build an array:

let read_array buf =
  (* Again, 8 for 8-byte doubles *)
  let length = String.length buf / 8 in
  Array.init length (fun i -> read_double buf i)

This is all untested, so beware of typos! There are likely ways to make it more efficient as well, although this implementation shouldn't be too bad for normal use.

Upvotes: 2

Related Questions