**已关闭。**此问题需要debugging details。目前不接受回答。
编辑问题以包括desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将帮助其他人回答问题。
7天前关闭
Improve this question的
我正在尝试用C++为hack汇编语言创建一个反汇编程序。现在我的问题在于将16位二进制转换回A指令。在我检查opCode之后,(第一位)为0,我必须将它后面的其他15位转换回前缀为“@"的十进制。转换工作一直到00000111111111并输出”@“1023 ',但00001111111111和更高版本仅输出'@2559 '。
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int BtoA (int n)
{
int num = n;
int decimal = 0;
int base = 0;
int tmp = num;
while (tmp != 0)
{
int last_dig = tmp % 10;
tmp /= 10;
decimal += last_dig * pow(2, base);
base++;
}
return decimal;
}
int main()
{
cout << "Welcome to the Hack Disassembler!\n";
int opCode;
int aIns;
cout << "\nIs the OP-Code 1 or 0? ";
cin >> opCode;
if (opCode == 0)
{
cout << "\nWhat are the other 15 bits? ";
cin >> aIns;
cout << "\nThat A Instruction is @" << BtoA(aIns) << "!\n";
}
}
字符串
1条答案
按热度按时间sulc1iza1#
尝试将变量
aIns
更改为类型std::string
。如果它是类型int
,则当您超过std::numeric_limits<int>::max()
时会溢出,对于32位整数,这是2'147'483'647
。这是一个10位数。当您添加第11位时,您会得到11'111'111'111
,溢出。个字符
关于
std::cin
的惊喜您的原始程序揭示了一个关于流输入的棘手事实:
假设你正在从流中提取一个类型为
IntType
的整数。它可以是int
,或者任何其他整数类型。当你从流中提取的值溢出类型IntType
时,值std::numeric_limits<IntType>::max()
将被静默替换。它并不是完全静默的,因为流也被置于失败状态。
如果不检查流是否失败,则可能无法捕捉流提取返回了“意外”值的事实。
在CppReference中,查找Stage 3: conversion and storage,您将在其中阅读以下内容:
如果v的类型是有符号整数类型,并且转换函数产生的正值或负值太大而无法容纳它,则最正或最负的可表示值分别存储在v中。
下面是一个演示:
型
当我们将
big_value
写入流,然后将其读入变量value
时,它会从2147483648
悄悄地更改为2147483647
。型
这正是OP所发生的事情,当他试图输入超过10位数的值时。