Creating binary from list variables?

Thomas Lindgren <>
Tue Dec 14 15:35:45 CET 2004

--- "Ericsson, Bjorn" <>

> 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

  %% Length is desired length, F filler byte
  Rem_length = Length-length(Lst),
  list_to_binary([Lst, lists:duplicate(Rem_length,

or something like that.
Sometimes you can exploit a special case:


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>>) ->
  trunc_binary(Bin) -> Bin.


Do you Yahoo!? 
Meet the all-new My Yahoo! - Try it today! 

More information about the erlang-questions mailing list