我试图在java中创建一个无符号乘法的算法。然后,该算法利用无符号和。这是代码:
public int[] unsignedSum(int[] n1, int[] n2){
int[] result = new int[48];
int carry = 0;
for(int x = 47; x >= 0; x--){
if (n1[x]+n2[x]+carry == 1){
result[x] = 1;
carry = 0;
}
else if (n1[x]+n2[x]+carry == 2)
carry = 1;
else if (n1[x]+n2[x]+carry == 3)
result[x] = 1;
}
return result;
}
public int[] unsignedMult(int[] n1, int[] n2){
int[] result = new int[48];
int[] N1 = new int[48];
int[] N2 = new int[48];
//fix the size to 48
for (int x = 24; x < 48; x++){
N1[x] = n1[x-24];
N2[x] = n2[x-24];
}
for(int x = 47; x >= 0; x--){
if (N2[x] == 1){
int[] shiftedN1 = new int[48];
for (int y = 0; y < x; y++)
shiftedN1[y] = N1[y+48-x];
result = unsignedSum(result, shiftedN1);
}
}
return result;
}
向量n1和n2的大小为24
任何其他矢量的大小为48
问题是:在某些情况下,它会吃掉第一个数字
乘法不应该溢出,但在这种情况下,它确实以某种方式
1100000 ...(24bits)* 1100000(24bits)..应该产生10010000 ...(48位),但它导致00100000 ......(48位)
答案 0 :(得分:1)
在
中查找2个逐个错误for (int y = 0; y < x; y++)
shiftedN1[y] = N1[y+48-x];
What is exactly the off-by-one errors in the while loop?
您可能需要手动运行上述循环,简单的情况是...... 0001 * .... 0001