|
|
| Author |
Message |
< Erlang ~ Printing binary stuff in base 16. |
| wolfgke |
Posted: Sun Dec 02, 2007 6:51 pm |
|
|
|
User
Joined: 16 Sep 2007
Posts: 16
|
An example:
Code: FooBar= <<255:8, 0:24>>.
io:format("~w~n", [FooBar]).
In this example the binary type is printed in base 10. Since such code is mainly used for debugging purposes it would be very useful to get the output in base 16.
So could please anybody help me. For numbers I can use
Code: io:format("~.16B~n", [FooBar]).
But this does not work for the binary type.
I also know I could convert the binary stuff to a number and print this - but is there a way to avoid this?
So please help me. |
|
|
| Back to top |
|
| francesco |
Posted: Sun Dec 02, 2007 10:25 pm |
|
|
|
User
Joined: 07 Jul 2006
Posts: 249
Location: London
|
Quote: But this does not work for the binary type.
I also know I could convert the binary stuff to a number and print this - but is there a way to avoid this?
The Erlang way would be to extract the integer from the binary and print it. If it is for debug purposes, why not... I would do something like this:
Code: 40> Bin = <<1,2,3,4,5>>.
<<1,2,3,4,5>>
41> <<Int:24, Rest/binary>> = Bin.
<<1,2,3,4,5>>
42> io:format("~.16b~n", [Int]).
10203
ok
43> Int.
66051
44>
Not as fun as having to write your own conversion functions as was custom in the good old days
Code: to_hex(Int) ->
to_hex(Int, []).
to_hex(0, Buff) -> Buff;
to_hex(Int, Buff) ->
to_hex(Int div 16, [to_char(Int rem 16)|Buff]).
to_char(Int) when Int > 9 -> Int rem 10 + $A;
to_char(Int) -> Int + $0.
Francesco
--
http://www.erlang-consulting.com |
|
|
| Back to top |
|
| wolfgke |
Posted: Mon Dec 03, 2007 3:37 pm |
|
|
|
User
Joined: 16 Sep 2007
Posts: 16
|
The reason why I want to avoid converting it to a number is endianness. It is an Erlang conversation of some rather ugly C code which depends a lot on little endian.
When I simply convert the binary to a number I always have to think whether the "wrong" byte oder is as it should or not - very error-prone I think.
The solution which I will probably take is letting some very nasty but little parts as a C function and call them by Erlang. |
|
|
| Back to top |
|
|
|
All times are GMT
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum You cannot attach files in this forum You cannot download files in this forum
|
|
|