Skip to content

Instantly share code, notes, and snippets.

@emauton
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emauton/34660d5de866abdf6544 to your computer and use it in GitHub Desktop.
Save emauton/34660d5de866abdf6544 to your computer and use it in GitHub Desktop.
% 16:21 < badmatch> Is there any way to create binary of given length from
% string, i.e. <<Name:(12*8)>> when Name can be larger
% (cut it) or smaller (add trailing zeros) than 12 bytes?
% nox's solution on-channel
-module(badmatch_question).
-compile(export_all).
-spec binary_with_zero_pad(string(), non_neg_integer()) -> binary().
binary_with_zero_pad(Str, N) ->
Bin = list_to_binary(lists:sublist(Str, N)),
<<Bin/binary, 0:(N - byte_size(Bin))/unit:8>>.
@igaray
Copy link

igaray commented Aug 29, 2014

courtesy of nox:

Bin = list_to_binary(lists:sublist(L, N)), <<Bin/binary,0:(N - byte_size(Bin))/unit:8>>.

@emauton
Copy link
Author

emauton commented Aug 29, 2014

Ah, thanks, just saw the comment when I edited. :o)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment