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

Bernard Duggan bernie@REDACTED
Sun Dec 21 12:58:28 CET 2008


Camille Troillard wrote:
> pad_to4 (Bin) ->
>     case (size(Bin) rem 4) of
> 0 -> Bin;
> Pad -> <<Bin/binary, 0:((4-Pad)*8)>>
>     end.
You can simplify this a little, making use of the fact that it's valid
to specify a size of 0 for part of a binary:

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

Or this if you're trying to keep your line count down :)

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

I don't think you can get it too much shorter than that though (but I'm
happy to be corrected).
Still not brilliantly elegant, but a bit simpler.

Cheers,

Beranrd



More information about the erlang-questions mailing list