[erlang-questions] Padding a binary to a multiple of 4 bytes

Nicolas Charpentier nc@REDACTED
Sun Dec 21 09:04:38 CET 2008


Camille Troillard wrote:
> Hi !
> 
> I am new to Erlang, and would like to ask experienced users some advices 
> on best practices I should adopt.
> 
> Right now, I would like to know what is the best way of padding a binary 
> to a multiple of 4 bytes.
> I have written a function like this:
> 
> pad_to4 (Bin) ->
>     case (size(Bin) rem 4) of
> 0 -> Bin;
> Pad -> <<Bin/binary, 0:((4-Pad)*8)>>
>     end.
> 
> I don't find it very elegant, and guess there is a better way of doing 
> this.  Perhaps using binary comprehensions?  What is your suggestion?
> 

pad_to4 (Bin) ->
	Padding_bits = (4 - (size(Bin) rem 4)) * 8,
	<<Bin/binary,0:Padding>>.



----
Nicolas Charpentier
http://charpi.net



More information about the erlang-questions mailing list