Interpret bytes as packed binary data

Hey, I am looking to interpret bytes as packed binary data. Like struct in python. I found cstruct in ocaml. Are there alternative libraries?

That’s a broad request and I don’t know what struct gives you in python.

In any case nowadays the stdlib has sized integer getters on string and getter and setters on bytes.

Depending on what you need to do – decode a binary format, or hide access to packed bytes behind an abstract type, that may be entirely sufficient.

If you need to parse binary data, check out

I have used Angstrom to parse binary data: fit parses the binary FIT format invented by Garmin for watches and other sensors that produce data for fitness activities. Angstrom can be used to parse both binary and textual data. If performance is important, it might not be the most efficient because it depends on back tracking.

Below is the code that parses the header of a FIT file.

let header =
    any_int8 >>= function
    | (12 | 14) as size ->
        any_int8 >>= fun protocol ->
        LE.any_int16 >>= fun profile ->
        LE.any_int32 >>= fun length ->
        string ".FIT"
        *> (if size = 14 then advance 2 (* skip CRC *) else advance 0)
        *> return { protocol; profile; length = Int32.to_int length }
    | n -> fail "found unexpected header of size %d" n
1 Like