Working with bit-level data

I plan to implement bitfields support in Cstruct library. And I wonder on what syntax is best and probably an API, maybe there are already some good examples of OCaml libraries that work with bit-level data? If you ask - why not to just aggregate bits into bytes, there are two problems:

  1. If you don’t align bitfields, all members can be shifted across byte boundary to be read directly
  2. Changing the way to read/write in case of different endianess

See https://github.com/mirage/ocaml-cstruct/issues/205 for more information.

Is https://github.com/xguerin/bitstring similar to what you are looking for?

1 Like

Yes, it is similar, thanks.

Note, that I sent an initial draft of bitfields implementation in Cstruct library (for now only reading is supported) here https://github.com/mirage/ocaml-cstruct/pull/215

You are welcome to check out, and feedback/complaints/patches are welcome.

It adds a syntax like this:

[%%cstruct
type some_struct = {
       field1: uint8_t;
       field2: uint32_t [@bits 15];
       field3: uint32_t [@bits 4];
       field4: uint16_t;
} [@@big_endian]]

which is an equivalent to C

struct some_struct {
       uint8_t field1;
       uint32_t field2:15;
       uint32_t field3:4;
       uint16_t field4;
} __attribute__ ((packed));
1 Like