c++ - 寻找二进制补码,
问题描述
这是要计算的代码:任何人,在帮助将有符号整数转换为其二进制等效值(8 位)(在 2 的补码中),反之亦然。程序应该能够 t0 首先读取用户提供的有符号整数或二进制数(始终为 2 的补码)
例如,当我输入00110101
转换为有符号十进制时,我会得到203
. 但正确答案是53
。
#include <iostream>
#include <string>
using namespace std;
string decimalToBinary(int);
string findTwosComplement(string);
string decimalToBinary(int n) {
if (n < 0)
n = 256 + n;
string res = "";
while (n > 0)
{
res = string(1, (char)(n % 2 + 48)) + res;
n = n / 2;
}
return res;
}
string decimalToBinary(int n) {
if (n < 0)
n = 256 + n;
string res = "";
while (n > 0)
{
res = string(1, (char)(n % 2 + 48)) + res;
n = n / 2;
}
return res;
}
string findTwosComplement(string s)
{
int num = s.length();
int i;
for (i = num - 1; i >= 0; i--)
if (s[i] == '1')
break;
if (i == -1)
return '1' + s;
for (int j = i - 1; j >= 0; j--)
{
if (s[j] == '1')
s[j] = '0';
else
s[j] = '1';
}
return s;
}
解决方案
我假设你想要这个用于教学目的,否则你只是这样做(signed char) n
。
这两个补码-2<<(n-1) + sum(2<<k for 0 <= k < n-1)
对于 8 位来说是数字的通常二进制表示,0 <= N < 128
不同之处在于最高有效位不是加 128,而是减 128。这就是它可以表示数字的原因-128 <= N < 128
。重要的是,您可以通过复制信号位来增加数字的宽度。C++ 数字已经是 2 补码 32 位数字,因此对于有效范围内的数字,24 个最高有效位要么全为“0”,要么全为“1”,因此您可以将这些位切片。
#include <iostream>
#include <string>
using namespace std;
string decimalToBinary(int n) {
// C++ integers are already in 2-complements so you only have to
// extract the bits.
if((n < -128) || (n >= 128)){
std::cerr << "The number "<< n << " does not fit into a 8-bit 2-complement representation" << std::endl;
}
string res = "";
for(int i = 0; i < 8; ++i){
res = string(1, (char)(((n >> i) & 1) + '0')) + res;
}
return res;
}
int binaryToDecimal(string s) {
// The most significant bit is the signal
int result = -((int)(s[0] - '0'));
for(int i = 1; i < s.size(); ++i){
result = 2*result + ((int)(s[i] - '0'));
}
return result;
}
int main(){
int input;
while(cin){
cout << "> ";
cin >> input;
string binary = decimalToBinary(input);
int output = binaryToDecimal(binary);
cout << input << " -> " << binary << " -> " << output << endl;
}
}
推荐阅读
- c# - SOAP HTTPS 服务在 c# 中使用
- android - Room SQLite 文件 - 确保所有更改都已刷新,并且在文件上传过程中没有 I/O
- sql - SSRS 参数删除其他过滤器
- logstash - 解析 nginx 错误日志的 grok 模式的问题
- php - 如何使用 PHP 将月份添加到特定日期?
- intel - 错误:无法安全地从此类存储库进行更新,因此默认禁用
- javascript - 未捕获的 URIError:尝试解码 var 时 URI 格式错误(javascript)
- c# - 当 RowState = Modified 时 SQLDataAdapter.Update() 不更新
- python - 命名两个或多个相关 Python 变量的首选方法是什么?
- python - 使用 os.walk 将多个文本文件转换为 csv