3

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.

TheSquad
  • 7,385
  • 8
  • 40
  • 79

2 Answers2

8

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

butter71
  • 2,703
  • 19
  • 12
  • 4
    To be honest, that documentation sucks hairy mooseballs. I've read and reread it over the past year and a half and the usage of the 'precision' argument for the base of the number to print is completely unclear. See how subtly your example is different from the one in the documentation: "~.16B" gives normal hex printing [now the Pad character == the base of the printed number] and in your version it is "16.0B" where the "P"(recision) field becomes the base of the number and the Pad character ('0' in this case) becomes the padding. Or I'm not getting it. – emvee Sep 24 '12 at 11:51
  • It is now 2018 and the exact same *terrible* documentation exists. In no place is there any indication that the precision field must now carry the base in order to use a field width. I think it is just a hack of notation since doing the pseudo logical thing would not match the documented ~F.P.PadModC. I think just a simple extension of the documentation to cover this case would have saved people 10s of thousands of hours over the years. After all, we all need to use different bases with a padded field width at times. – uDude Mar 23 '18 at 17:28
0

Transform 42 (Base 10) into "000002A" (Base 16) in Erlang:

> io_lib:format("~8.16.0B", [42]).
> "0000002A"