Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing integer in hexadecimal with Elixir

I can do this in Erlang:

io:fwrite("~.16X~n", [-31,"0x"]).
-0x1F
ok

but not in Elixir:

:io.fwrite("~.16X~n", [-31,"0x"]) ** (ArgumentError) argument error (stdlib) :io.format(#PID<0.54.0>, "~.16X~n", [-31, "0x"])

Why not?

like image 830
z1naOK9nu8iY5A Avatar asked May 23 '26 21:05

z1naOK9nu8iY5A


2 Answers

Why not to use Integer.to_string/2?

iex(1)> Integer.to_string(-31, 16)
"-1F"
like image 85
Grych Avatar answered May 27 '26 00:05

Grych


Adding @Dogbert's comment as an answer:

Try using single quotes:

:io.fwrite('~.16X~n', [-31, '0x'])

A word of additional explanation: single quotes in Elixir indicate a character list (see here for more details). The Erlang fwrite function is expecting a list of characters not an Elixir binary hence the double quotes don't work while the single quotes do.

like image 39
Onorio Catenacci Avatar answered May 27 '26 00:05

Onorio Catenacci