Given a sequence of zeros and ones, e.g.,
1101110
I would like to sum all the elements of the sequence, and write the result in base 2, by using only logical operations between 0s and 1s. In this example, the sum is equal to 5, which in base 2 reads
101
and which is the desired result.
I know a simple way of achieving this, which consists in
- writing zero in base 2:
000
- adding to it the first bit in the sequence, i.e.
1
, and obtain001
. This can be done with a XOR operation. - adding the second bit to
001
, and obtain010
, with a XOR operation and an AND operation to compute the carry. - proceed in the same way for the remaining bits.
I suspect that this method is far from being optimal in terms of number of operations. Do you guys know a more efficient method?