[erlang-questions] simple question: how to convert integers to string with fixed digits
Håkan Stenholm
hokan.stenholm@REDACTED
Sat Dec 1 19:46:42 CET 2007
Matej Kosik wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Håkan Stenholm wrote:
>> Matej Kosik wrote:
>>
>> You can experiment with the io:format(...) (or io_lib:format(...))
>> string, this works in you case:
>>
>> 6> io:format("~2..0w", [2]).
>> 02
>>
>> 10> io:format("~2.16.0B", [255]).
>> FF
>>
>
> These procedures work fine. Reading the manual I was not able to recognize such possibilities. They
> print the term on the terminal in the way I need it.
>
> These parameters also kind be used with
>
> io_lib:fwrite/2
>
> even though its results, for example in these cases:
>
> io_lib:fwrite("~2.16.0B", [12]).
>
> is weird
>
> [["0","C"]]
>
> I would expect:
>
> ["0C"]
>
> Nonetheless the weird returned object seems to behave as the expected string.
io_lib.erl has tendency to create strings similar to io_lists (io_list()
= [char() | binary() | io_list()]), there are efficiency reason for
doing it like this, e.g. appending two strings like ["foo" | "bar"]
during pretty printing formating is O(1) rather than O(N) which "foo" ++
"bar" - which could in some circumstances result in O(N^2) issues.
You might need to use lists:flatten/1 (O(N log N)) if you need a proper
string() - [char()], rather than a nested list of chars and lists.
One reason why io_lib doesn't apply lists:flatten/1 on it's output is
another efficiency consideration - when sending byte streams over
networks or to disk, it is quite simple to traverse the nested (tree)
structure in O(N log N) time* thereby minimizing the amount of
operations needed to process the strings**, this is useful when the data
is mainly intended to be passed on to other processes/servers/users.
* functions/modules that accept io_list() will do this as well
as a number of other io related functions
** you save a O(N) traversal over the flattend string
>
> Thank you
> - --
> Matej Kosik
> -----BEGIN PGP SIGNATURE-----
> Version: GnuPG v1.4.6 (GNU/Linux)
> Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org
>
> iD8DBQFHUaB3L+CaXfJI/hgRApwQAKC8UYMBaWMeKdFQhlMr9Fq+O2t4QQCg1CPb
> cHjy/9B656Xr+FtX935lboE=
> =NFxh
> -----END PGP SIGNATURE-----
>
More information about the erlang-questions
mailing list