why
why

Reputation: 24851

How to split Erlang binary in special length?

I open one udp socket and want to split the binary packet I received to every 10 bytes. Is there any api or good method ? thanks!

Upvotes: 0

Views: 928

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170723

Here is one way to do it:

split(Bin, LenPart) -> 
  lists:reverse(split1(Bin, LenPart, [])).

split1(Bin, LenPart, Acc) when byte_size(Bin) =< LenPart -> 
  [Bin | Acc];
split1(Bin, LenPart, Acc) -> 
  <<Part:LenPart/binary, Rest/binary>> = Bin,
  split1(Rest, LenPart, [Part | Acc]).

Upvotes: 3

Related Questions