Compute the sum of the two input bitsets. - Java java.util

Java examples for java.util:BitSet

Description

Compute the sum of the two input bitsets.

Demo Code


//package com.java2s;
import java.util.*;

public class Main {
    /**//from   www .j av a 2  s .c  om
     * Compute the sum of the two input bitsets.
     * 
     * @param carryIn The carry in to the lower order bit position.
     * @param bs1 One operand.
     * @param bs2 Another operand.
     *
     * @return The sum.
     */
    public static BitSet SumCarry(boolean carryIn, BitSet bs1, BitSet bs2) {

        BitSet sum = new BitSet();
        boolean carry = carryIn;
        int size = Math.max(bs1.size(), bs2.size());

        for (int index = 0; index < size; index += 1) {
            boolean bit1 = bs1.get(index);
            boolean bit2 = bs2.get(index);

            if (bit1 && bit2 && carry) {
                carry = true;
                sum.set(index, true);
            } else if ((bit1 && bit2) || ((bit1 || bit2) && carry)) {
                carry = true;
                sum.set(index, false);
            } else if (bs1.get(index) || bs2.get(index) || carry) {
                carry = false;
                sum.set(index, true);
            } else {
                carry = false;
                sum.set(index, false);
            }
        }
        if (carry)
            sum.set(size);
        return sum;
    }
}

Related Tutorials