Printf.printf and 'Bytes' argument

With Printf.printf “%s…” we can directly insert a “String” argument.

What about inserting a “Bytes” argument?

1 Like

I believe that was overlooked when rushing in the bytes stuff. It would indeed both be logical and convenient if there was such a thing.

1 Like

You can use Printf.printf "%s" (Bytes.to_string b).

or Printf.printf "%a" output_bytes bytes.

It saves a copy so in theory it’s more efficient, but I don’t like that it works only for Printf.printf and Printf.fprintf.


In many cases Bytes.unsafe_of_string is reasonable to use in a Printf expression. Clearly depends on the case, but have a look at the Unsafe conversion chapter in the ocaml manual

@mseri I believe you mean Bytes.unsafe_to_string (“to”) to convert it to a string. :wink:

Having to use memory-unsafe type coercion to produce a printf converter for bytes kind of defeats the point of having a nicely typed printf module in the first place IMHO.

1 Like

There’s some discussion about this in Mantis PR 6429: A format specifier for bytes.

One option for the moment is to use ppx_custom_printf, which allows you to write %{Bytes} as the format specifier, like this:

let b = Bytes.of_string "abc" in
Printf.printf !"a bytes value: %{Bytes}.\n" b