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

Richard O'Keefe ok@REDACTED
Mon Dec 22 04:51:15 CET 2008


> 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.

While we're at it, let's generalise:

pad_to(Width, Binary) ->
     case (Width - size(Binary) rem Width) rem Width
       of 0 -> Binary
        ; N -> <<Binary/binary, 0:(N*8)>>
     end.

Now that 64-bit machines are so very common, padding to 8
makes a lot of sense too.




More information about the erlang-questions mailing list