[erlang-questions] Padding a binary to a multiple of 4 bytes
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
>> 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)>>
>> I don't find it very elegant, and guess there is a better way of
>> this. Perhaps using binary comprehensions? What is your suggestion?
> pad_to4 (Bin) ->
> 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>>.
> Nicolas Charpentier
> erlang-questions mailing list
More information about the erlang-questions