Skip to content

Instantly share code, notes, and snippets.

@mks-m
Created October 24, 2008 11:34
Show Gist options
  • Save mks-m/19393 to your computer and use it in GitHub Desktop.
Save mks-m/19393 to your computer and use it in GitHub Desktop.
% list of {type, flag} tuples
pack(List) -> pack(List, <<>>).
pack([], Ready) -> Ready;
pack([{Type, Flag}|Rest], Ready) ->
Bit = ?MODULE:Type(Flag) - 1,
Size = size(Ready) * 8,
io:format("switch bit ~p in ~p bits~n", [Bit, Size]),
switch(Bit, Size, Rest, Ready).
switch(Bit, Size, Rest, Ready) when Bit >= Size ->
BB = (Bit - Size) rem 8,
Zeros = ((Bit - Size) div 8) * 8,
NewReady = <<Ready/binary,
0:Zeros/integer,
(1 bsl BB):8/integer>>,
pack(Rest, NewReady);
switch(Bit, _, Rest, Ready) ->
ByteNum = max(Bit div 8, 0),
<<PreByte:ByteNum/binary,
Byte:8/integer,
PostByte/binary>> = Ready,
BB = Bit - (Bit div 8) * 8,
NewByte = Byte bor (1 bsl BB),
NewReady = <<PreByte/binary,
NewByte:8/integer,
PostByte/binary>>,
pack(Rest, NewReady).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment