BitwiseAnd.java

Download
1/*2 * BitwiseAnd.java3 *4 * Computer Science E-22/S-225 *6 * A class that contains a recursive method for determining the7 * bitwise AND of two binary numbers represented as strings.8 *9 * The main method includes two examples of using this method.10 */11 12public class BitwiseAnd {13    /*14     * bwAnd - takes two bitstrings b1 and b2 -- i.e.,15     * two strings composed of 0 or more 0s and 1s -- and 16     * determines the bitwise AND of the corresponding 17     * binary numbers.18     * 19     * assumption: b1 and b2 are strings composed of 0 or 20     * more 0s or 1s21     */22    public static String bwAnd(String b1, String b2) {23        if (b1.equals("") || b2.equals("")) {24	        return "";25	    } else {26            int last1 = b1.length() - 1;27            int last2 = b2.length() - 1;	     28            String andRest = bwAnd(b1.substring(0, last1),29                                   b2.substring(0, last2));30	        if (b1.charAt(last1) == '1' 31              && b2.charAt(last2) == '1') {32	            return andRest + "1";33	        } else {34	            return andRest + "0";35            }36        }37    }38 39    public static void main(String[] args) {40        System.out.print("bitwise AND of 11101 and 11011: ");41        System.out.println(bwAnd("11101", "11011"));42 43        System.out.print("bitwise AND of 1010101 and 1100: ");44        System.out.println(bwAnd("1010101", "1100"));45    }46}