c++ - 将十进制转换为 8 位二进制补码 C++
问题描述
任务是将十进制值转换为 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;;
}
解决方案
使用 stringstream 和 mask 的解决方案和解释
二进制补码
在二进制补码表示法中,非负数由其普通二进制表示法表示;在这种情况下,最高有效位是 0。但是,表示的数字范围与无符号二进制数的范围不同。例如,一个 8 位无符号数可以表示值 0 到 255 (11111111)。
然而,二进制补码 8 位数只能表示从 0 到 127 (01111111) 的正整数,因为其余最高有效位为“1”的位组合表示负整数 -1 到 -128。
#include <sstream>
#include <cstring>
#include <iostream>
using namespace std;
string DecimalToBinary(int n) {
stringstream ss((n < 0) ? "1" : "0"); // the first bit, for any integer, indicates if its negative or not
if (n < 0)
n = -(n+1); // read about two complement!
int mask = 1 << 6; // Since int8_t has only 8 bits you just need to have your mask initialized to 2^6 (equivalent to 0b01000000) as your initial mask that will help you to detect the 7 following bits, from left to right.
while (mask) {
ss << ((mask & n) ? "1" : "0"); // if the bit of the mask matches the bit of n then we add it to the string.
mask >>= 1; // 0b01000000 becomes 0b00100000 and so on
}
return ss.str();
}
也改变:
cout << userInput << " = " << DecimalToBinary(dec) << "\n";
或者,您可以使用缓冲区 char 数组来保留您的方法,但其长度只需要 9 个字符:第一个 char 是符号(“1”表示负数,“0”表示 pos),然后是 7 位生成值, 和 '\0' 结束字符串。
二进制补码运算是加法逆运算,所以负数用绝对值的二进制补码表示。
推荐阅读
- django - 如何使用 django 中的 postgres 数据库使用(用户名、电子邮件、密码、年龄和性别)创建登录和注册表单?
- python - ARIMA 模型在新的 statsmodels ARIMA for python 中无法正常工作
- android - Kotlin Multiplatform 错误:指令与文件位置不匹配
- javascript - 如何从语音通道中获取用户ID
- excel - 如果范围有多个列,如何确定具有目标值的单元格的地址?
- flutter - 在 Flutter 中请求 url 后从响应中获取数据
- java - Springboot递归方法为Async
- android - Jetpack Compose:Modifier.heightIn(...) 与 Modifier.prefferedHeigh(...) 有什么区别
- regression - 使用像梯度提升这样的线性回归
- sql - Oracle 数据库中的 VARCHAR