在 C++ 中添加二进制数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13282825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:09:13  来源:igfitidea点击:

Adding binary numbers in C++

c++binaryadd

提问by Muhammad Arslan Jamshaid

How would I add two binary numbers in C++? What is the correct logic?

如何在 C++ 中添加两个二进制数?什么是正确的逻辑?

Here is my effort, but it doesn't seem to be correct:

这是我的努力,但似乎不正确:

#include <iostream>
using namespace std;
int main()
{
    int a[3];
    int b[3];
    int carry = 0;
    int result[7];

    a[0] = 1;
    a[1] = 0;
    a[2] = 0;
    a[3] = 1;

    b[0] = 1;
    b[1] = 1;
    b[2] = 1;
    b[3] = 1;

    for(int i = 0; i <= 3; i++)
    {
        if(a[i] + b[i] + carry == 0)
        {
            result[i] = 0;
            carry = 0;
        }

        if(a[i] + b[i] + carry == 1)
        {
            result[i] = 0;
            carry = 0;
        }

        if(a[i] + b[i] + carry == 2)
        {
            result[i] = 0;
            carry = 1;
        }

        if(a[i] + b[i] + carry > 2)
        {
            result[i] = 1;
            carry = 1;
        }
    }
    for(int j = 0; j <= 7; j++)
    {
        cout<<result[j]<<" ";
    }
    system("pause");
}

回答by krammer

Well, it is a pretty trivial problem.

嗯,这是一个非常微不足道的问题。

How to add two binary numbers in c++. what is the logic of it.

c++中如何将两个二进制数相加。它的逻辑是什么。

For adding two binary numbers, a and b. You can use the following equations to do so.

用于将两个二进制数 a 和 b 相加。您可以使用以下等式来执行此操作。

sum = a xor b

carry = ab

总和 = a xor b

进位 = ab

This is the equation for a Half Adder.

这是半加器的等式。

Now to implement this, you may need to understand how a Full Adderworks.

现在要实现这一点,您可能需要了解全加器的工作原理。

sum = a xor b xor c

carry = ab+bc+ca

sum = a xor b xor c

进位 = ab+bc+ca

Since you store your binary numbers in int array, you might want to understand bitwise operation. You can use ^ for XOR,| operator for OR, & operator for AND.

由于您将二进制数存储在 int 数组中,因此您可能想了解按位运算。您可以使用 ^ 进行异或,| OR 运算符,AND 运算符。

Here is a sample code to calculate the sum.

这是计算总和的示例代码。

for(i = 0; i < 8 ; i++){
   sum[i] = ((a[i] ^ b[i]) ^ c); // c is carry
   c = ((a[i] & b[i]) | (a[i] & c)) | (b[i] & c); 
}

回答by bitmask

Since you were asking about C++, you deserve a C++ answer. Use bitsets:

既然您问的是 C++,那么您应该得到 C++ 的答案。使用位

#include <bitset>
#include <iostream>

int main() {
  std::bitset<5> const a("1001");
  std::bitset<5> const b("1111");
  std::bitset<5> const m("1");
  std::bitset<5> result;
  for (auto i = 0; i < result.size(); ++i) {
    std::bitset<5> const diff(((a >> i)&m).to_ullong() + ((b >> i)&m).to_ullong() + (result >> i).to_ullong());
    result ^= (diff ^ (result >> i)) << i;
  }
  std::cout << result << std::endl;
}

This works for arbitrarily long bit sets.

这适用于任意长的位集。

回答by Karthik T

There is a bug :

有一个错误:

if(a[i]+b[i]+carry==1)  
{   
result[i]=1; 
carry=0;  
}  

Also u might want to print in reverse

你也可能想反向打印

for(int j=6; j>=0; j--)  
{  
   cout<<result[j]<<" ";  
}

回答by dreamcrash

You could use "Bitwise OR" operation to reduce the code since

您可以使用“按位或”操作来减少代码,因为

1 or 1 = 1
1 or 0 = 1
0 or 1 = 1
0 or 0 = 0

You could also convert both number to decimal sum and them go back to binary again.

您也可以将两个数字都转换为十进制和,然后再将它们转换回二进制。

Converting decimal to binary

十进制转二进制

int toBinary (unsigned int num, char b[32])
    {
    unsigned  int x = INT_MIN;      // (32bits)
    int i = 0, count = 0;
    while (x != 0)
    {
      if(x & num) // If the actual o bit is 1 & 1 = 1 otherwise = 0
      {
          b[i] = '1';
          count++;
      }
      else b[i] = '0';

      x >>=1;       // pass to the left
      i++;          
    }
    return count;
    }

回答by molbdnilo

Your arrays are one item too small for your indexing.

您的数组对于您的索引来说太小了。

int a[3]only has 3 elements, so a[3] = 1is invalid (it has undefined behaviour) since it's accessing the 4th element, which doesn't exist.
Likewise for the other arrays.

int a[3]只有 3 个元素,因此a[3] = 1无效(它具有未定义的行为),因为它正在访问不存在的第 4 个元素。
其他阵列也是如此。

That means that the whole program has undefined behaviour, i.e. it can do anything or nothing at all.

这意味着整个程序具有未定义的行为,即它可以做任何事情或根本不做任何事情。

(What's probably happening in your case is that writing outside the arrays is overwriting the other variables.)

(在您的情况下可能发生的是在数组外写入会覆盖其他变量。)

You're also not initialising the resultarray, so its content is just some random data.
Since you only update 4 of its elements but print all of them (and more), the output will be random data as well.

你也没有初始化result数组,所以它的内容只是一些随机数据。
由于您只更新了其中的 4 个元素但打印了所有元素(以及更多),因此输出也将是随机数据。

回答by Aadil Imran

Following were the errors in your code and fixed code is also below"

以下是您的代码中的错误,固定代码也在下面”

  1. int a[] was of size 3 so it cannot store at the 3rd index. use int a[4].
  2. if(a[i]+b[i]+carry==1) wrong values were assigned in this check update result[i]=1; carry=0.
  3. The sequence of checks is reversed.
  4. The last carry was not stored in the result.
  5. The addition result stored in the result array was in reverse order so printed it in reverse.
  1. int a[] 的大小为 3,因此它无法存储在第 3 个索引处。使用 int a[4]。
  2. if(a[i]+b[i]+carry==1) 本次校验更新 result[i]=1 赋值错误;进位=0。
  3. 检查顺序相反。
  4. 最后的进位没有存储在结果中。
  5. 结果数组中存储的加法结果顺序相反,因此将其反向打印。

here is the working piece of code:

这是工作代码:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    int a[4];
    int b[4];
    int carry=0;
    int result[5];


    a[0]=1;
    a[1]=0;
    a[2]=0;
    a[3]=1;

    b[0]=1;
    b[1]=1;
    b[2]=1;
    b[3]=1;

    for(int i=0; i<4; i++)
    {

        if(a[i]+b[i]+carry==3)
        {
        result[i]=1;
        carry=1;
        }
        if(a[i]+b[i]+carry==2)
        {
        result[i]=0;
        carry=1;
        }
        if(a[i]+b[i]+carry==1)
        {
        result[i]=1;
        carry=0;
        }
        if(a[i]+b[i]+carry==0)
        {
        result[i]=0;
        carry=0;
        }


    }
    result[4]=carry;
    for(int j=4; j>=0; j--)
    {
        cout<<result[j];

    }
    cout<<endl;

        return 0;
}

回答by Manglesh Pareek

#include <stdio.h>



int main()

{



    long binary1, binary2;

    int i = 0, remainder = 0, sum[20];



    printf("Enter the first binary number: ");

    scanf("%ld", &binary1);

    printf("Enter the second binary number: ");

    scanf("%ld", &binary2);

    while (binary1 != 0 || binary2 != 0)

    {

        sum[i++] =(binary1 % 10 + binary2 % 10 + remainder) % 2;

        remainder =(binary1 % 10 + binary2 % 10 + remainder) / 2;

        binary1 = binary1 / 10;

        binary2 = binary2 / 10;

    }

    if (remainder != 0)

        sum[i++] = remainder;

    --i;

    printf("Sum of two binary numbers: ");

    while (i >= 0)

        printf("%d", sum[i--]);

    getch();
    return 0;

}

回答by bingchuan zhang

you should do this

你应该做这个

for(int i = 3; i >= 0; i--)
    {
        if(a[i] + b[i] + carry == 0)
        {
            result[i] = 0;
            carry = 0;
        }
        else if(a[i]+b[i]+carry==1)
        {
            result[i]=1;
            carry=0;  
        }
        else if(a[i] + b[i] + carry == 2)
        {
            result[i] = 0;
            carry = 1;
        }
        else if(a[i] + b[i] + carry > 2)
        {
            result[i] = 1;
            carry = 1;
        }
        printf("%d",result[i]);
    }

回答by fedemengo

A non-conventional solution, but it works:

一个非常规的解决方案,但它有效:

int main() {

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

  int size = sizeof(A)/sizeof(*A);

  int C[size+1];
  int t = 0;

  for(int i = size-1; i > -1; i--){

      C[i+1] = A[i]+B[i]+t;
      t = C[i+1]/2;
      C[i+1] %= 2;
  }

  C[0] = t;
}

回答by Mattlab

What if their sizes are not the same? Also, you would want to allow the user to input the binary numbers (in this case representing integers) as integers and not as elements of arrays. Here is a piece of code that accomplishes those :-)

如果它们的大小不一样怎么办?此外,您希望允许用户将二进制数(在本例中表示整数)作为整数而不是数组元素输入。这是一段完成这些的代码:-)

#include <iostream>
using namespace std; 

// Add two numbers in binary

void sumBinary(int num1, int num2, int* sum12){
    int mod1 = 0;
    int mod2 = 0;
    int carry = 0;
    int factor = 1;

    int flag = 0;

    *sum12 = 0;

    while (!flag){
        mod1 = num1 % 10;
        mod2 = num2 % 10;

        num1 /= 10;
        num2 /= 10;
        if ((carry + mod1 + mod2) == 2){
            *sum12 += 0;
            carry = 1;
        }
        else if ((carry + mod1 + mod2) == 3){
            *sum12 += factor;
            carry = 1;
        }
        else if ((carry + mod1 + mod2) == 0){
            *sum12 += 0;
            carry = 0;
        }
        else{
            *sum12 += factor;
            carry = 0;
        }
        factor *= 10;
        if ((num1 == 0) && (num2 == 0)){ 
            *sum12 += carry*factor;
            flag = 1; }


    }
}
void main(){
    int num1, num2, sum12;

    cout << "Enter the first binary integer number: ";
    cin >> num1;
    cout << "Enter the second binary integer number: ";
    cin >> num2;

    sumBinary(num1, num2, &sum12);

    cout << "The sum in binary form is :" << sum12 << endl;
}