如何在C++中添加两个二进制数?什么是正确的逻辑?
这是我的努力,但它似乎不正确:
#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");
}
Run Code Online (Sandbox Code Playgroud)
kra*_*mer 20
嗯,这是一个非常微不足道的问题.
如何在c ++中添加两个二进制数.它的逻辑是什么?
添加两个二进制数,a和b.您可以使用以下等式来执行此操作.
sum = a xor b
carry = ab
这是半加法器的等式.
现在要实现这一点,您可能需要了解Full Adder的工作原理.
sum = a xor b xor c
carry = ab + bc + ca.
由于您将二进制数存储在int数组中,因此您可能希望了解按位运算.您可以使用^表示XOR,| OR的运算符,AND的运算符.
以下是计算总和的示例代码.
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);
}
Run Code Online (Sandbox Code Playgroud)
由于您正在询问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;
}
Run Code Online (Sandbox Code Playgroud)
这适用于任意长的位集。