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

Camille Troillard <>
Sat Dec 20 14:03:56 CET 2008


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?

Also, I was wondering why the "/binary" suffix was needed if I want to
append to the Bin variable.  Intuitively, I have written <<Bin, 0:size>>,
but it doesn't work.


Thanks in advance for your help!


Best,
Camille
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20081220/73bbd320/attachment.html>


More information about the erlang-questions mailing list