c++针对二进制补码算术中整数的算术运算问题，请大神指点

c++ 二进制问题请教

01001和10010的二进制和是11011。

#include iostream>
#include cmath>
#include string>

using namespace std;

int main()
{
//Read in the bit pattern size
int L;
do {
cout << "Enter positive integer for the bit pattern size ";
cin >> L;
}while (L <= 0);

``````    //Read in two integers a and b
int a, b;
cout << "Enter an integer a ";
cin >> a;
cout << "Enter an integer b ";
cin >> b;

//Calculate the decimal arithmetic sum of a and b and print the result int
c1 = a + b;
cout << "In decimal " << a << " + " << b << " is " << c1 << endl;

//Compute the two's complement representations of a and b
//Each integer must be represented in L-bits pattern
//Also these two's complement representations must be returned as string data types
string A = decimalToTwocomplementString(a, L);
string B = decimalToTwocomplementString(b, L);

//Print the two's complement representations of a and b
cout << "The two's complement of " << a << " is\t " << A << endl;
cout << "The two's complement of " << b << " is\t " << B << endl;

//Compute the binary sum of the two's complement representations of a and b
//The result must be returned as L-bit pattern string data type

//Print the two's complement representation binary sum
cout << "The binary sum of " << A << " and " << B << " is " << C << endl;

//Convert the two's complement representation binary sum to decimal and print
int c2 = TwoComplementStringToDecimal(C);
cout << "In two's complement arithmetic, " << a << " + " << b << " is " << c2 << endl;

//Print some concluding results
if (c1 == c2) cout << c1 << " is equal to " << c2 << ". Good Job!" << endl;
else
``````

{
cout << c1 << " is not equal to " << c2 << endl;
cout << "Either " << c1 << " cannot be represented by the given bit pattern OR we have made some mistake!" << endl;
}
system("Pause");
return 0;
}

6个回答

``````#include <iostream>
#include <string>
#include <cmath>

using namespace std;

string decimalToTwocomplementString(int num, int length) {
string binary;
int positive_num = abs(num);
while (positive_num != 0) {
if (num >= 0){
binary.insert(0,to_string(positive_num & 1));
positive_num >>= 1;
} else {
binary.insert(0,to_string(!(positive_num & 1)));
positive_num >>=1;
}
}
if (num < 0) {
for (reverse_iterator it = binary.rbegin(); it != binary.rend(); it++) {
if (*it == '1') {
*it = '0';
} else {
*it = '1';
break;
}
}
}
while (binary.length() < length) {
if (num >= 0) {
binary.insert(0, "0");
} else {
binary.insert(0, "1");
}
}
return binary;
}

string TwoComplementStringAddition (const string& a, const string& b) {
int carry = 0;
string result;
for (reverse_iterator ita = a.rbegin(), itb = b.rbegin(); ita != a.rend(); ita++, itb++) {
int num_a = *ita - '0';
int num_b = *itb - '0';
result.insert(0,to_string(num_a ^ num_b ^ carry));
if (num_a == 1 && num_b == 1) {
carry = 1;
} else if (num_a == 0 && num_b == 0) {
carry = 0;
}
}
return result;
}

int TwoComplementStringToDecimal(string binary) {
int result = 0;
string::iterator it = binary.begin();
bool negative = *it == '1';
if (negative) {
for (; it != binary.end(); it++) {
*it = *it == '1' ? '0' : '1';
}
for (reverse_iterator iterator = binary.rbegin(); iterator != binary.rend(); iterator++) {
if (*iterator == '1') {
*iterator = '0';
} else {
*iterator = '1';
break;
}
}
}
for (it = binary.begin(); it != binary.end(); it++) {
result += (*it - '0') * pow(2,distance(it,binary.end()) - 1);
}
return negative ? -result : result;
}

int main()
{
//Read in the bit pattern size
int L;
do {
cout << "Enter positive integer for the bit pattern size ";
cin >> L;
}while (L <= 0);

//Read in two integers a and b
int a, b;
cout << "Enter an integer a ";
cin >> a;
cout << "Enter an integer b ";
cin >> b;

//Calculate the decimal arithmetic sum of a and b and print the result int
int c1 = a + b;
cout << "In decimal " << a << " + " << b << " is " << c1 << endl;

//Compute the two's complement representations of a and b
//Each integer must be represented in L-bits pattern
//Also these two's complement representations must be returned as string data types
string A = decimalToTwocomplementString(a, L);
string B = decimalToTwocomplementString(b, L);

//Print the two's complement representations of a and b
cout << "The two's complement of " << a << " is\t " << A << endl;
cout << "The two's complement of " << b << " is\t " << B << endl;

//Compute the binary sum of the two's complement representations of a and b
//The result must be returned as L-bit pattern string data type

//Print the two's complement representation binary sum
cout << "The binary sum of " << A << " and " << B << " is " << C << endl;

//Convert the two's complement representation binary sum to decimal and print
int c2 = TwoComplementStringToDecimal(C);
cout << "In two's complement arithmetic, " << a << " + " << b << " is " << c2 << endl;

//Print some concluding results
if (c1 == c2) cout << c1 << " is equal to " << c2 << ". Good Job!" << endl;
else

{
cout << c1 << " is not equal to " << c2 << endl;
cout << "Either " << c1 << " cannot be represented by the given bit pattern OR we have made some mistake!" << endl;
}
return 0;
}

``````

gd6179 感谢大神指导，学艺不精，我再仔细琢磨。谢谢！

gd6179 应该不会这么难，入门级的，没搞懂

11011是补码，反码就是11010，源码就是10101=-5，哪里不懂吗？

``````#include <string>
#include <stdlib.h>

string decimalToTwocomplementString(int a, int L)
{
string result = "";
while(L > 0)
{
result += std::toString(a % 2);
a /= 2;
L--;
}
}

int TwoComplementStringToDecimal(string C)
{
return strtol(C.c_str(), NULL, 2);
}

{
return decimalToTwocomplementString(TwoComplementStringToDecimal(A) + TwoComplementStringToDecimal(B));
}

``````

PS:
1.题目中要求不能用数组变量，但没有规定不能用C函数，

2.要是支持C++11就更简单了，参考C++11 stol函数和fmt::FormatInt。

``````string decimalToTwocomplementString(int num, int length) {
string binary;
int positive_num = abs(num);
//判断正负，正数的补码就是原码，而负数的补码是在原码的基础上按位取反再加1
while (positive_num != 0) {
//如果是正数，直接取其原码
if (num >= 0){
binary.insert(0,to_string(positive_num & 1));
positive_num >>= 1;
//如果是负数，先取它的反码
} else {
binary.insert(0,to_string(!(positive_num & 1)));
positive_num >>=1;
}
}
//如果是负数，将之前获取到的反码加1，得到补码
//由于这个是字符串，所以没有真正意义上的加1，而是根据二进制数的性质，从右向左遍历
//找到第一个是0的数，把这个0变成1，再把之前遍历到的所有1改成0，就相当于加1了
if (num < 0) {
for (reverse_iterator it = binary.rbegin(); it != binary.rend(); it++) {
if (*it == '1') {
*it = '0';
} else {
*it = '1';
break;
}
}
}
//如果当前的字符串长度小于输入的二进制位数
//是正数则前面补0，负数则前面补1
while (binary.length() < length) {
if (num >= 0) {
binary.insert(0, "0");
} else {
binary.insert(0, "1");
}
}
return binary;
}

``````

``````string TwoComplementStringAddition (const string& a, const string& b) {
//代表是否有进位
int carry = 0;
string result;
//从右向左遍历这俩字符串
//因为这俩字符串长度一定是一样的，所以终止条件写谁都无所谓
for (reverse_iterator ita = a.rbegin(), itb = b.rbegin(); ita != a.rend(); ita++, itb++) {
//把当前遍历到的位的值转换成整型
int num_a = *ita - '0';
int num_b = *itb - '0';
//将当前这俩数值与进位数异或，获得当前位置相加后的结果
result.insert(0,to_string(num_a ^ num_b ^ carry));
//当这俩字符串当前数值都是1时，肯定发生进位
//而且在有进位的前提下，只要当前这俩数值不是0和0那么一定会再次发生进位
if (num_a == 1 && num_b == 1) {
carry = 1;
} else if (num_a == 0 && num_b == 0) {
carry = 0;
}
}
return result;
}
``````

``````int TwoComplementStringToDecimal(string binary) {
int result = 0;
string::iterator it = binary.begin();
//判断这个二进制数的符号位是1还是0
//来决定这个数是正还是负
bool negative = *it == '1';
//如果是负数，要把补码转换为原码
//和原码转补码是同样的过程
//这里我为了偷懒，把符号位也给变成0了，但实际上负数的原码符号位是1
if (negative) {
for (; it != binary.end(); it++) {
*it = *it == '1' ? '0' : '1';
}
for (reverse_iterator iterator = binary.rbegin(); iterator != binary.rend(); iterator++) {
if (*iterator == '1') {
*iterator = '0';
} else {
*iterator = '1';
break;
}
}
}
//加权求值
for (it = binary.begin(); it != binary.end(); it++) {
result += (*it - '0') * pow(2,distance(it,binary.end()) - 1);
}
return negative ? -result : result;
}

``````

gd6179 但要求是不改变程序也不更改函数名，实现缺失函数，使程序运行正确。可编写额外的帮助函数，从函数中调用，但不能对程序做修改。请大神指导。谢谢！

``````#include <iostream>
#include <cmath>
#include <string>

using namespace std;

/*Implement code begin */
string decimalToTwocomplementString(int a, int L)
{
string result = "";

//In our computer, int type save as complement itself! So we can save it to string directly with enough length.
//For example in 32bit computer, -14 saved as 0xFFFFFFFFFFFFFFF2,
//We only need 5 length to record in this question which is 0x12 (= binrary10010)
//And as a positive number, 0x5(=01001) don't have sign bit.
while(L-- > 0) {
result += (a & 0x1) ? string("1"):string("0");
a >>= 1;
}
return result;
}

int TwoComplementStringToDecimal(string C)
{
int len = C.length();
int num = 0;

//Translate string to positive number
for(int i = 0; i < len; i++)
{
num <<= 1;
if('0' != C[i])
num |= 1;
}

if(len > 0 && '1' == C[0]) {
//It's negative number, we can change it back.
//in this case, our number is 0x12, we need to change back to 0xFFFFFFFFFFFFFFF2
num |= (~0 << len);
}
cout << "transfer" << C << "to" << num;
return num;
}

{
return decimalToTwocomplementString(TwoComplementStringToDecimal(A) + TwoComplementStringToDecimal(B), A.length());
}

/*Implement code End */

int main()
{
//Read in the bit pattern size
int L;
do {
cout << "Enter positive integer for the bit pattern size ";
cin >> L;
}while (L <= 0);

//Read in two integers a and b
int a, b;
cout << "Enter an integer a ";
cin >> a;
cout << "Enter an integer b ";
cin >> b;

//Calculate the decimal arithmetic sum of a and b and print the result int
int c1 = a + b;
cout << "In decimal " << a << " + " << b << " is " << c1 << endl;

//Compute the two's complement representations of a and b
//Each integer must be represented in L-bits pattern
//Also these two's complement representations must be returned as string data types
string A = decimalToTwocomplementString(a, L);
string B = decimalToTwocomplementString(b, L);

//Print the two's complement representations of a and b
cout << "The two's complement of " << a << " is\t " << A << endl;
cout << "The two's complement of " << b << " is\t " << B << endl;

//Compute the binary sum of the two's complement representations of a and b
//The result must be returned as L-bit pattern string data type

//Print the two's complement representation binary sum
cout << "The binary sum of " << A << " and " << B << " is " << C << endl;

//Convert the two's complement representation binary sum to decimal and print
int c2 = TwoComplementStringToDecimal(C);
cout << "In two's complement arithmetic, " << a << " + " << b << " is " << c2 << endl;

//Print some concluding results
if (c1 == c2) cout << c1 << " is equal to " << c2 << ". Good Job!" << endl;
else
{
cout << c1 << " is not equal to " << c2 << endl;
cout << "Either " << c1 << " cannot be represented by the given bit pattern OR we have made some mistake!" << endl;
}

//system("Pause");
return 0;
}
``````

PS: 突然发现下午看题忘记填补码,而且include缺少stdlib.h，楼上代码应该是个解（不细看啦），先赞一个。

gd6179 感谢大神指导。谢谢！！

c++针对二进制补码算术中整数的算术运算问题，请大神指点
c++ 二进制问题请教 以下程序针对二进制补码算术中整数的算术运算问题，要求先确定一个bit pattern size ，然后第一个函数要把输入的两个整数转化为二进制输出，第二个函数把两个二进制数相加输出，第三个函数再把结果转化回十进制。 只使用c++字符串数据类型，不使用任何数组变量。不改变主程序也不更改函数名，实现缺失函数，使程序运行正确。可编写额外的帮助函数，从函数中调用但不能对程序做修改。 需要使用c++字符串数据类型来表示这两个二进制补码的表示形式，不能使用任何数组变量，可使用字符串变量作为一个整体或使用索引访问字符串中变量中的字符。 程序示例运行如下 输入位模式大小的正整数：5 输入整数A：9 输入整数B：-14 十进制 9 + -14 = -5 二进制补码9 是 01001 二进制补码-14 是 10010 01001和10010的二进制和是11011。 在二进制补码计算中，9＋ -14=-5。 #include iostream> #include cmath> #include string> using namespace std; int main() { //Read in the bit pattern size int L; do { cout << "Enter positive integer for the bit pattern size "; cin >> L; }while (L <= 0); //Read in two integers a and b int a, b; cout << "Enter an integer a "; cin >> a; cout << "Enter an integer b "; cin >> b; //Calculate the decimal arithmetic sum of a and b and print the result int c1 = a + b; cout << "In decimal " << a << " + " << b << " is " << c1 << endl; //Compute the two's complement representations of a and b //Each integer must be represented in L-bits pattern //Also these two's complement representations must be returned as string data types string A = decimalToTwocomplementString(a, L); string B = decimalToTwocomplementString(b, L); //Print the two's complement representations of a and b cout << "The two's complement of " << a << " is\t " << A << endl; cout << "The two's complement of " << b << " is\t " << B << endl; //Compute the binary sum of the two's complement representations of a and b //The result must be returned as L-bit pattern string data type string C = TwoComplementStringAddition(A, B); //Print the two's complement representation binary sum cout << "The binary sum of " << A << " and " << B << " is " << C << endl; //Convert the two's complement representation binary sum to decimal and print int c2 = TwoComplementStringToDecimal(C); cout << "In two's complement arithmetic, " << a << " + " << b << " is " << c2 << endl; //Print some concluding results if (c1 == c2) cout << c1 << " is equal to " << c2 << ". Good Job!" << endl; else { cout << c1 << " is not equal to " << c2 << endl; cout << "Either " << c1 << " cannot be represented by the given bit pattern OR we have made some mistake!" << endl; } system("Pause"); return 0; } **_原程序拷屏如下：_** ![图片说明](https://img-ask.csdn.net/upload/201807/06/1530848793_765945.jpg) ![图片说明](https://img-ask.csdn.net/upload/201807/06/1530848804_675124.jpg)

Java学习的正确打开方式

Python 植物大战僵尸代码实现(2):植物卡片选择和种植

【搞定 Java 并发面试】面试最常问的 Java 并发基础常见面试题总结！

2019年互联网寒冬，大批企业开始裁员，下图是网上流传的一张截图： 裁员不可避免，那如何才能做到不管大环境如何变化，自身不受影响呢？ 我们先来看一个有意思的故事，如果西游记取经团队需要裁员一名，会裁掉谁呢，为什么？ 西游记团队组成： 1.唐僧 作为团队teamleader，有很坚韧的品性和极高的原则性，不达目的不罢休，遇到任何问题，都没有退缩过，又很得上司支持和赏识(直接得到唐太宗的任命，既给
shell脚本：备份数据库、代码上线

iOS Bug 太多，苹果终于坐不住了！

《Neural Networks and Deep Learning》读书笔记第四篇本章其实和前面章节的关联性不大，所以大可将本章作为小短文来阅读，当然基本的深度学习基础还是要有的。主要介绍了神经⽹络拥有的⼀种普遍性，比如说不管目标函数是怎样的，神经网络总是能够对任何可能的输入，其值（或者说近似值）是网络的输出，哪怕是多输入和多输出也是如此，我们大可直接得出一个结论：不论我们想要计算什么样的函数，...

IntelliJ IDEA 简称 IDEA，被业界公认为最好的 Java 集成开发工具，尤其在智能代码助手、代码自动提示、代码重构、代码版本管理(Git、SVN、Maven)、单元测试、代码分析等方面有着亮眼的发挥。IDEA 产于捷克，开发人员以严谨著称的东欧程序员为主。IDEA 分为社区版和付费版两个版本。 我呢，一直是 Eclipse 的忠实粉丝，差不多十年的老用户了。很早就接触到了 IDEA...

Redis 面试题 1、什么是 Redis?. 2、Redis 的数据类型？ 3、使用 Redis 有哪些好处？ 4、Redis 相比 Memcached 有哪些优势？ 5、Memcache 与 Redis 的区别都有哪些？ 6、Redis 是单进程单线程的？ 7、一个字符串类型的值能存储最大容量是多少？ 8、Redis 的持久化机制是什么？各自的优缺点？ 9、Redis 常见性...

【超详细分析】关于三次握手与四次挥手面试官想考我们什么？

Vue快速实现通用表单验证

2019年Spring Boot面试都问了什么？快看看这22道面试题！
Spring Boot 面试题 1、什么是 Spring Boot？ 2、Spring Boot 有哪些优点？ 3、什么是 JavaConfig？ 4、如何重新加载 Spring Boot 上的更改，而无需重新启动服务器？ 5、Spring Boot 中的监视器是什么？ 6、如何在 Spring Boot 中禁用 Actuator 端点安全性？ 7、如何在自定义端口上运行 Sprin...
【图解】记一次手撕算法面试：字节跳动的面试官把我四连击了

【图解算法面试】记一次面试：说说游戏中的敏感词过滤是如何实现的？

GitHub 标星 1.6w+，我发现了一个宝藏项目，作为编程新手有福了！

java知识体系整理，学会了，月入过万不是梦

2020年去一线大厂面试先过SSM框架源码这一关！
SSM框架介绍 （1）持久层（Mybatis）：Dao层（mapper） DAO层：DAO层主要是做数据持久层的工作，负责与数据库进行联络的一些任务都封装在此。 DAO层的设计首先是设计DAO的接口。 然后在Spring的配置文件中定义此接口的实现类。 然后就可在模块中调用此接口来进行数据业务的处理，而不用关心此接口的具体实现类是哪个类，显得结构非常清晰。 DAO层的数据源配置，以及有...

Java程序员必备基础：内部类解析

Java9到Java13各版本新特性代码全部详解(全网独家原创)
Java现在已经发展到了Java13了（正式版本），相信很多朋友还对各个版本还不是很熟悉，这里面专门把Java9到Java13各个版本的一些新特性做了一些详细讲解。我在网上也找了很多，但基本都是官方文档的CV，没有任何代码演示，而且官方的示例代码也不是很好找得到，官方API目前还是Java10，官方文档真是坑啊。所以我在这里专门写了一篇文章，主要针对平时开发与有关的功能Java9到Java13各...

By 超神经场景描述：春节马上就要来临，在这个假期里，怎么能让自己放松，又不至于生疏了自己的老本行？不妨来玩一下编程向的小游戏吧，超神经在此整理了三款好玩有趣又有深度的游戏，快看看是不是...
2020年JVM面试题吐血整理【过年必看】
2B哥今天给大家带来点jvm相关的面试题，希望小伙伴们可以在春节这段时间好好复习下。看完这篇JVM面试基本没问题。95%内容都在在，更多的面试题可以关注公众号（微信搜：java2b） 1、内存模型以及分区，需要详细到每个区放什么。 JVM 分为堆区和栈区，还有方法区，初始化的对象放在堆里面，引用放在栈里面， class 类信息常量池（static 常量和 static 变量）等放在方法区 new...

CPU对每个程序员来说，是个既熟悉又陌生的东西？ 如果你只知道CPU是中央处理器的话，那可能对你并没有什么用，那么作为程序员的我们，必须要搞懂的就是CPU这家伙是如何运行的，尤其要搞懂它里面的寄存器是怎么一回事，因为这将让你从底层明白程序的运行机制。 随我一起，来好好认识下CPU这货吧 把CPU掰开来看 对于CPU来说，我们首先就要搞明白它是怎么回事，也就是它的内部构造，当然，CPU那么牛的一个东...
Python实战：抓肺炎疫情实时数据，画2019-nCoV疫情地图

Web前端开发高级前端技术（高级开发程序篇）
（给达达前端加星标，提升前端技能）内容有点多，也请你静下来，慢阅读，今后多多关照。说到web前端开发高级，必须要掌握的是HTML和css代码的优化，前端优化很重要，这是成功你进阶的道路上...