实现Booth算法的算术右移

时间:2014-03-07 02:10:42

标签: java string algorithm logic computer-architecture

我试图使用Java实现Booth的算法,但是我的rightShift()函数中忽略了算术右移函数(multiply())。是因为我为product变量使用了一个字符串吗?这是我的代码: -

import java.util.Scanner;
class BoothsAlgorithm{
    static String appendZeros(int n){
        String result = "";
        for(int i = 0; i < n; i++) result += "0";
        return result;
    }
    static String rightShift(String str){
        String result = "";
        for(int i = 0; i < str.length(); i++){
            if(i == 0) result += str.charAt(i);
            else result += str.charAt(i-1);
        }
        return result;
    }
    static String add(String a, String b){
        String result = "";
        char carry = '0';
        for(int i = a.length()-1; i >= 0; i--){
            String condition = "" + a.charAt(i) + b.charAt(i) + carry;
            switch(condition){
                case "000": result = "0" + result; break;
                case "001": result = "1" + result; carry = '0'; break;
                case "010": result = "1" + result; break;
                case "011": result = "0" + result; break;
                case "100": result = "1" + result; break;
                case "101": result = "0" + result; break;
                case "110": result = "0" + result; carry = '1'; break;
                case "111": result = "1" + result; break;
            }
        }
        return result;
    }
    static String multiply(int a, int b){
        String op1 = Integer.toBinaryString(a);
        String op2 = Integer.toBinaryString(b);
        String negop2 = Integer.toBinaryString(-b);
        char prev = '0';
        String product = appendZeros(64-op1.length())+op1;
        for(int i = 0; i < 32; i++){
            if(i > 0) prev = product.charAt(63);
            if(product.charAt(63)=='0' && prev == '1'){
                String temp = appendZeros(32-op2.length()) + op2 + appendZeros(32);
                product = add(product, temp);
            }
            if(product.charAt(63)=='1' && prev == '0'){
                String temp = appendZeros(32-negop2.length()) + negop2 + appendZeros(32);
                product = add(product, temp);
            }
            rightShift(product);
        }
        return product.substring(32);
    }
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the first number: ");
        int operand1 = sc.nextInt();
        System.out.print("Enter the second number: ");
        int operand2 = sc.nextInt();
        System.out.println("The multiplication is "+multiply(operand1, operand2));
    }
}

1 个答案:

答案 0 :(得分:1)

您需要product = rightShift(product);或类似。 rightShift返回包含其结果的新String。它不会也不能更改调用者中product引用的字符串。