所以我一直在为我的C ++课程开发一个项目,我们必须创建一个二进制计算器。然而教授说这些函数应该返回一个8位二进制集。我的问题是这个
11111111 + 11111111 = 0111111110
然而,在我们最初创建的函数中,这就是结果
11111111 + 1111111 = 00000000
对我而言不正确。所以我把我的功能改成了
十进制到二进制
string DecToBin(int num)
{
/*
Purpose: Changing a Decimal to a Binary Set
Pre: Valid positive integer
Post: Returns the valid binary string
*/
string bin = "";
while (num >= 0)
{
bin += (num % 2 == 0 ? "0" : "1");
if (num != 0)
num /= 2;
else break;
}
return bin;
}
虽然这里又出现了问题
01010101 + 10101010 = 011111111
但我上面的函数返回
01010101 + 10101010 = 111111110
如果我需要返回一个8位集,或者如果我上面说的函数返回正确的答案,对于其他函数我需要弄清楚为什么那样,那么创建最好的函数是什么?首先。
二进制到十进制
int BinToDec(string bin)
{
/*
Purpose: To generate a decimal integer from a string binary set
Pre: Valid String binary set
Post: Output the output decimal integer
*/
int output = 0; //initialize output as 0
int base2Start = 128;//base2 start at 128
int len = bin.length();//get the string length
for (int i = 0; i < len; i++)//iterate
{
if (bin[i] == '1')//if bin[i] in the array of string is a char 1
{
output = output + base2Start;//output gets + base2Start
}//end if condition
base2Start = base2Start / 2;//divide base2Start after each iteration
}//end for loop
return output;//return the output
}
添加功能
int Addition(string st1, string st2)
{
/*
Purpose: Get's two valid Binary sets, then adds their decimal conversion, and returns the addition
Pre: Need two strings that SHOULD be valid binary
Post: Returns binary from decimal conversion
*/
int first, second;
if (ValidBin(st1))
{
first = BinToDec(st1);
}
else return 0;
if (ValidBin(st2)){
second = BinToDec(st2);
}
else return 0;
add++;
return first + second;
}
答案 0 :(得分:1)
bin += (num % 2 == 0 ? "0" : "1");
应该是
bin = (num % 2 == 0 ? "0" : "1") + bin;
因为您每次将num
的最低有效位添加到字符串。因此,最后,根据您的代码,您将获得最不重要的最左侧而不是最右侧。
编辑:要将结果截断为8位宽,请更改以下行:
return first + second;
通过这个:
return (first + second) & 0xFF; // Same as (first + second) % 256
答案 1 :(得分:0)
#include <iostream>
using namespace std;
string sumBinary (string s1, string s2);
int main()
{
cout << "output = "<< sumBinary ("10","10");
}
string sumBinary (string s1, string s2)
{
if (s1.empty())
return s2;
if (s2.empty())
return s1;
int len1 = s1.length() -1;
int len2 = s2.length() -1;
string s3;
s3 = len1 > len2 ? s1: s2;
int len3 = s3.length() -1;
bool carry = false;
while (len1>=0 || len2>=0) {
int i1 = len1>=0? s1[len1--] - '0': 0;
int i2 = len2>=0? s2[len2--] - '0': 0;
// Check if any invalid character
if (i1 <0 || i1>1 || i2<0 || i2>1)
return "";
// 3 bit sum
int sum = i1 ^ i2 ^ carry;
// 3 bit carry
carry = (i1 & carry) | (i2 & carry) | (i1 & i2);
s3[len3--] = '0' + sum;
}
if (carry)
s3 = "1" + s3;
return s3;
}