用环绕式c ++二进制加两个数字

时间:2013-11-18 10:16:27

标签: c++ arrays binary

前一天我问了一个关于添加两个二进制数的问题。我的问题解决了。值是C很好,但现在我在环绕中遇到麻烦。为了处理环绕值,我在S中创建了另一个数组S和C的复制值(通过A和B的二进制加法获得)。执行加法直到进位变为零。该值被复制正常,但更改后S垃圾值保存在S.我不知道什么是错的。任何人都可以帮忙。提前致谢。这是代码

char C[9]={'\0','\0','\0','\0','\0','\0','\0','\0','\0'};
char B[9]={'1','1','0','0','0','1','1','1','\0'};
char A[9]={'1','1','0','0','0','0','1','1','\0'};

char carry='0';
char sum[9]={'\0','\0','\0','\0','\0','\0','\0','\0','\0'};
for(int i = 7; i >= 0; i--) {
    C[i] = ((A[i] ^ B[i]) ^ carry); 
    carry = ((A[i] & B[i]) | (A[i] & carry)) | (B[i] & carry);
}

strcpy(sum,C);
for(int l = 7; carry!='0'; l--) {
sum[l] = (C[l]) ^ (carry);
carry = C[l] & carry;
}

cout << endl << sum << endl;

2 个答案:

答案 0 :(得分:2)

我认为你应该简单地使用整数而不是char。如下所示。

#include <iostream>
using namespace std;

int main() {

  int B[8]={1,1,0,0,0,1,1,1};
  int A[8]={1,1,0,0,0,0,1,1};

  int carry=0;
  int sum[8]={0,0,0,0,0,0,0,0};
  for(int i = 7; i >= 0; i--) {
      sum[i] = ((A[i] ^ B[i]) ^ carry); 
      carry = ((A[i] & B[i]) | (A[i] & carry)) | (B[i] & carry);
  }

  if ( carry ) {
    int carryArray[8] = {0,0,0,0,0,0,0,1};
    carry = 0;
    for(int i = 7; i >= 0; i--) {
      sum[i] = ((A[i] ^ carryArray[i]) ^ carry); 
      carry = ((A[i] & carryArray[i]) | (A[i] & carry)) | (carryArray[i] & carry);
    }
  }

  for(int l = 0; l < 8; l++) {
    cout << sum[l];
  }

  cout << endl;
  return 0;
}

答案 1 :(得分:1)

更好的方法是仅使用按位运算符(您可以考虑右移和左移)并对整数进行操作。

问题是你在ASCII值0和1上操作,而不是在0和1上操作。所以明智地减去/加'0'。

char carry='0';
char sum[9]={'\0','\0','\0','\0','\0','\0','\0','\0','\0'};

for(int i = 7; i >= 0; i--) {
    C[i] = ((((A[i] - '0') ^ (B[i] - '0')) ^ (carry- '0'))) + '0'; 
    carry = ((((A[i] - '0') & (B[i] - '0')) | ((A[i] - '0') & (carry - '0'))) | ((B[i] - '0') & (carry - '0'))) + '0';
}

strcpy(sum, C);

for(int l = 7; carry != '0'; l--) {
    sum[l] = ((C[l] - '0') ^ (carry - '0')) + '0';
    carry = ((C[l] - '0') & (carry - '0'))+ '0'; //be careful about operator precedence.
}