Creating binary from list variables?
Thomas Lindgren
thomasl_erlang@REDACTED
Tue Dec 14 15:35:45 CET 2004
--- "Ericsson, Bjorn" <Bjorn.Ericsson@REDACTED>
wrote:
> How do I create a binary, to send with gen_tcp:send,
> from variables of
> different types and dynamic length, when I want the
> final binary to be of
> fixed length? (As it usually is defined in socket
> interfaces)
As far as I know, you have to pad what you send
yourself:
%% Length is desired length, F filler byte
Rem_length = Length-length(Lst),
list_to_binary([Lst, lists:duplicate(Rem_length,
F)])
or something like that.
Sometimes you can exploit a special case:
<<0:Rem_length/unsigned-integer-unit:8>>
creates a binary of Rem_length zeroes.
Neither of these truncate a too long message, of
course. Here is one approach (if you don't care what
gets lost):
trunc_binary(<<TruncBin:124/binary,_/binary>>) ->
TruncBin;
trunc_binary(Bin) -> Bin.
Best,
Thomas
__________________________________
Do you Yahoo!?
Meet the all-new My Yahoo! - Try it today!
http://my.yahoo.com
More information about the erlang-questions
mailing list