Search code examples
formattingioerlang

Erlang: How to transform a decimale into a Hex string filled with zeros


I would like to transform 42 (Base 10) into 000002A (Base 16) in Erlang...

I have found some pointers on the web :

io:format("~8..0B~n", [42]) -> 00000042

And

io:format("~.16B~n", [42]) -> 2A

But I cannot seems to find how to do both at the same time, I have tried :

io:format("~8..0.16B~n", [42])

Which seemed to be the logical thing, but it is not, it gives me an error.

Thanks.


Solution

  • io:format("~8.16.0B~n", [42]).
    0000002A

    basically, it's ~F.P.Pad where:

    • F = field width
    • P = precsion
    • Pad = pad character

    see the full io:format docs