在 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);
}
相关文章