【发布时间】:2021-02-23 05:26:49
【问题描述】:
任务是将十进制值转换为 8 位二进制补码。输入需要介于 -128 和 127 之间。目前,我的程序仅适用于正数。我在编码方面相当新,所以我一直卡住,希望能提供任何帮助。
#include <iostream>
#include <string>
using namespace std;
int DecimalToBinary(int dec);
int main() {
int userInput;
cout << "Enter a value: ";
cin >> userInput;
if (userInput >= -128 && userInput <= 127) {
int dec = userInput;
cout << userInput << " = ";
DecimalToBinary(dec);
}
else {
cout << "Enter a value between -128 and 127: ";
cin >> userInput;
if (userInput >= -128 && userInput <= 127)
{
int dec = userInput;
cout << userInput << " = ";
DecimalToBinary(dec);
}
}
return 0;
}
int DecimalToBinary(int dec)
{
int bin[1000] = {}; // array to store binary number
int i = 0;
while (dec > 0) { //calculating the binary
bin[i] = dec % 2; //storing remainder
dec = dec / 2;
++i;
}
// printing binary in 8 bit & reverse order
int bits = 8;
if (i > 8) {
bits = 8 * ((i + 7) / 8);
}
for (int j = bits - 1; j >= 0; j--) {
cout << bin[j];
}
return dec;;
}
【问题讨论】:
-
这能回答你的问题吗? What is “2's Complement”?
-
程序不是已经在做赋值要求的事情了吗:接受一个整数输入,并将其作为 8 位二进制值输出?您所在的系统很可能是二进制补码系统,因此整数输入的格式已经正确。
标签: c++ twos-complement