[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  
>> 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>>.
>
You need an extra rem to cover the case,  size(Bin) rem 4 = 0!

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

Again but using unit:8 and band

pad_to4(Bin) ->
	<<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




More information about the erlang-questions mailing list