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

Richard O'Keefe <>
Mon Dec 22 03:47:51 CET 2008


On 21 Dec 2008, at 2:03 am, 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,

I don't either, because of the excess parentheses around
"size(Bin) rem 4", and because "Pad" is *not* the amount
of padding required, but the amount of padding NOT required.
Also, "to4" is rather ugly.  Treat "4" as a word here.

How about
	pad_to_4(Binary) ->
	    case (4 - size(Binary) rem 4) rem 4
	      of 0 -> Binary
	       ; N -> <<Binary/binary, 0:(N*8)>>
	    end.

Tested, works, doesn't copy unless it has to.




More information about the erlang-questions mailing list