2015-04-19 61 views
0

我想在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位)

回答

1

寻找2 off-by在

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 ....

+0

我发誓,我再也找不到这个错误由​​我自己,你救了我的一天。 – none

+0

*你救了我的周末 – none

+1

*你救了我整个星期 – none