
表示为位流的无符号数以二进制形式写入。
54 的二进制形式是 110110。
使用位将两个数字相加,我们将把它们相加使用二进制加法逻辑的二进制形式。
位加法的规则是 -
立即学习“C++免费学习笔记(深入)”;
我们举个例子,将两个数字相加,
Input: a = 21 (10101) , b = 27 (11011) Output: 48 (110000)
解释 - 10101 + 11011 = 110000。我们将从最低有效位开始添加位。然后传播到下一位。
#include <bits/stdc++.h>
#define M 32
using namespace std;
int binAdd (bitset < M > atemp, bitset < M > btemp){
bitset < M > ctemp;
for (int i = 0; i < M; i++)
ctemp[i] = 0;
int carry = 0;
for (int i = 0; i < M; i++) {
if (atemp[i] + btemp[i] == 0){
if (carry == 0)
ctemp[i] = 0;
Else {
ctemp[i] = 1;
carry = 0;
}
}
else if (atemp[i] + btemp[i] == 1){
if (carry == 0)
ctemp[i] = 1;
else{
ctemp[i] = 0;
}
}
else{
if (carry == 0){
ctemp[i] = 0;
carry = 1;
}
else{
ctemp[i] = 1;
}
}
}
return ctemp.to_ulong ();
}
int main () {
int a = 678, b = 436;
cout << "The sum of " << a << " and " << b << " is ";
bitset < M > num1 (a);
bitset < M > num2 (b);
cout << binAdd (num1, num2) << endl;
}The sum of 678 and 436 is 1114
以上就是使用C++中的位运算,将两个无符号数相加的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号