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

Tony Rogvall <>
Sun Dec 21 13:38:12 CET 2008

```On 21 dec 2008, at 09.04, Nicolas Charpentier wrote:

> Camille Troillard wrote:
>> Hi !
>>
>> I am new to Erlang, and would like to ask experienced users some
>> 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:
>>
>>    case (size(Bin) rem 4) of
>> 0 -> Bin;
>>    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?
>>
>
> 	Padding_bits = (4 - (size(Bin) rem 4)) * 8,
>
You need an extra rem to cover the case,  size(Bin) rem 4 = 0!

Padding_bits = ((4 - (size(Bin) rem 4)) rem 4)*8,

Again but using unit:8 and band

<<Bin/binary, 0:(((4- (size(Bin) band 16#3)) band 16#3))/unit:8>>.

/Tony

>
>
> ----
> Nicolas Charpentier
> http://charpi.net
> _______________________________________________
> erlang-questions mailing list
>
> http://www.erlang.org/mailman/listinfo/erlang-questions

```