Adding binary numbers in 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++ 中添加二进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中添加二进制数
基础教程推荐
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
