[erlang-questions] unexpected result of term_to_binary

Joe Armstrong erlang@REDACTED
Mon Jan 21 21:41:07 CET 2013


On Mon, Jan 21, 2013 at 8:46 PM, Paul Davis <paul.joseph.davis@REDACTED>wrote:

> In Erlang a list of integers in the range 0-255 is a string.
>

No it's not - a list of integers in the range 0-255 is not a string - it's
a list of integers
from 0-255 and nothing else - you don't  a clue what it represents.

Example:

> Ages = [65,66,67].
"ABC"

is a list of the ages (integers) at which many people become pensioners in
Sweden - it's also three ascii characters codes for 'A' 'B' and 'C'.

All erlang knows is that this is a list of three integers it hasn't a clue
what it means.

The shell prints this as "ABC" (this is a string literal representing the
integers [65,66,67])  This is because the shell prints a list of printable
character codes as a string literal, ie it guesses that the intended
meaning is as a list of character codes and prints it as a string to help
you.

In this case the shell guessed wrong. It's a list of ages :-)

We can use io:format to change the printed representation

> io:format(" ~s ~w ~p~n", [Ages, Ages,Ages]).
ABC [65,66,67] "ABC"

Ages is a list of three integers.

/Joe


> An easy test is to show that the value 256 changes the encoding into a
> list of integers:
>
> > term_to_binary([1, 2, 3, 4, 256]).
> <<131,108,0,0,0,5,97,1,97,2,97,3,97,4,98,0,0,1,0,106>>
>
>
>
> On Mon, Jan 21, 2013 at 1:38 PM, Steve Davis <
> steven.charles.davis@REDACTED> wrote:
>
>> The following appears to encode lists of integers as strings (?!?):
>>
>> Eshell V5.9.3  (abort with ^G)
>> 1> term_to_binary([1,2,3,4]).
>> <<131,107,0,4,1,2,3,4>>
>>
>> Is there a reason for this that I'm missing?
>>
>> regs,
>> /s
>>
>> _______________________________________________
>> erlang-questions mailing list
>> erlang-questions@REDACTED
>> http://erlang.org/mailman/listinfo/erlang-questions
>>
>
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20130121/827c7d98/attachment.htm>


More information about the erlang-questions mailing list