在 C++ 中添加二进制数

Adding binary numbers in C++(在 C++ 中添加二进制数)
本文介绍了在 C++ 中添加二进制数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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");
}

推荐答案

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

Well, it is a pretty trivial problem.

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

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

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

sum = a xor b

sum = a xor b

carry = ab

这是半加法器的等式.

现在要实现这一点,您可能需要了解 Full Adder 的工作原理.

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

sum = a xor b xor c

sum = a xor b xor c

进位 = ab+bc+ca

carry = ab+bc+ca

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

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.

这是一个计算总和的示例代码.

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); 
}

这篇关于在 C++ 中添加二进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)