2015-04-19 63 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