Skip to content

Instantly share code, notes, and snippets.

@sebastian
Created November 2, 2010 17:31
Show Gist options
  • Save sebastian/659971 to your computer and use it in GitHub Desktop.
Save sebastian/659971 to your computer and use it in GitHub Desktop.
Does binary addition of two bitstrings of equal length and throws away the carry.
-spec(add_bitstrings/2::(Bin1::bitstring(), Bin2::bitstring()) -> bitstring()).
add_bitstrings(Bin1, Bin2) when bit_size(Bin1) =:= bit_size(Bin2) ->
add_bit_with_carry(bit_size(Bin1), Bin1, Bin2, false).
add_bit_with_carry(0, Acc, _Bin, _Carry) -> Acc;
add_bit_with_carry(BitNumber, AccBin1, Bin2, Carry) ->
Bit = BitNumber - 1,
<<Beginning:Bit/bitstring, B1:1/bitstring, Rest/bitstring>> = AccBin1,
<<_DontYetCare:Bit/bitstring, B2:1/bitstring, _Rest/bitstring>> = Bin2,
{NextBit, NextCarry} = case {B1, B2, Carry} of
{<<0:1>>, <<0:1>>, true} -> {1, false};
{<<0:1>>, <<0:1>>, false} -> {0, false};
{<<0:1>>, <<1:1>>, true} -> {0, true};
{<<0:1>>, <<1:1>>, false} -> {1, false};
{<<1:1>>, <<0:1>>, true} -> {0, true};
{<<1:1>>, <<0:1>>, false} -> {1, false};
{<<1:1>>, <<1:1>>, true} -> {1, true};
{<<1:1>>, <<1:1>>, false} -> {0, true}
end,
<<_:7/bitstring, B:1/bitstring>> = <<NextBit>>,
add_bit_with_carry(Bit,
<<Beginning:Bit/bitstring, B:1/bitstring, Rest/bitstring>>,
Bin2, NextCarry).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment