c++ - 超过 64 位时的未定义行为

标签 c++ 64-bit overflow

我编写了一个将十进制数转换为二进制数的函数。我以 long long int 形式输入我的十进制数。它适用于小数字,但我的任务是确定计算机如何处理溢出,所以当我输入 (2^63) - 1 时,函数输出十进制值为 9223372036854775808,二进制等于 -954437177。当我输入 2^63 这是一个 64 位机器无法保存的值时,我收到警告,整数常量太大以至于它是无符号的,十进制常量仅在 ISO C90 中是无符号的,十进制的输出值为负 2^63,二进制数为 0。我使用 gcc 作为编译器。这样的结果对吗?

代码如下:

#include <iostream>
#include<sstream>
using namespace std;
int main()
{
long long int answer;
long long dec;
string binNum;
stringstream ss;
cout<<"Enter the decimal to be converted:"<< endl;;
cin>>dec;
cout<<"The dec number is: "<<dec<<endl;
while(dec>0)
{
     answer = dec%2;
     dec=dec/2;
     ss<<answer;
     binNum=ss.str();
}
cout<<"The binary of the given number is: ";
for (int i=sizeof(binNum);i>=0;i--){
     cout<<binNum[i];}
return 0;
    }

最佳答案

首先,“在 64 位计算机上”是没有意义的:无论计算机如何,long long 都保证至少是 64 位。如果可以将现代 C++ 编译器压入 Commodore 64 或 Sinclair ZX80,或者 KIM-1,long long 仍将至少是 64 位。这是 C++ 标准提供的与机器无关的保证。

其次,指定过大的值与“溢出”相同。

唯一让这个问题有点意思的是有区别。而且该标准对这两种情况的处理方式不同。对于使用整数值初始化有符号整数的情况,如有必要,将执行转换,如果无法表示该值,则具有实现定义的效果,......

C++11 §4.7/3: “If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined”

而对于例如产生不能由参数类型表示的值的乘法,效果是不确定的(例如,甚至可能崩溃)......

C++11 §5/4: “If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined.”

关于代码我是在写完上面的代码后才发现的,但它看起来确实会在足够大的数量下产生溢出(即未定义的行为)。将您的数字放在 vectorstring 中。请注意,您也可以只使用 bitset 来显示二进制数字。

哦,KIM-1。没有多少人熟悉它,所以这是一张照片:

KIM-1 single-board computer

据报道,尽管键盘有些受限,但它非常好。

关于c++ - 超过 64 位时的未定义行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12343690/

相关文章:

c++ - std::swap 不调用我的自定义交换实现 c++11

vim - Vim 可以打开的最大文件大小是多少? (64 位)

assembly - 我的 .exe 程序不是我所期望的

css - 级联 CSS 菜单中的溢出问题

c++ - cin 如何拆分整数序列?

c++ - Qt 隐式共享类 - 调用函数按值传递和返回的成本高吗?

c++ - 初始化C++ 11风格的单例

c++ - 从 32 位迁移到 64 位 - OpenCV/MinGW/Eclipse

css - 如何将 Jquery Mobile 嵌入到容器中?

c# - 带溢出的简单区间/范围交集