c++ - 十六进制加减法

标签 c++ hex

到目前为止我有这段代码。当我将两个负整数相加时,答案是正数而不是负数。我该如何解决? 我认为 0x80000000 是整数的最小可能值

#include <iostream>
#include <string>

using namespace std;

int main(void)
{
unsigned int maxInt = 0x7FFFFFFF;
int num1 = 7;
signed int minInt = 0x80000000;
int num2 = -21;
float num3 = 1;
float i;

cout<<"The value of the first variable is: "<<maxInt<<endl;
cout<<"The value of the second variable is: "<< num1<<endl;
cout<<"Addition of the two numbers: "<< maxInt + num1 <<endl;
cout<<endl;

cout<<"The value of the first variable is: "<<minInt<<endl;
cout<<"The value of the second variable is "<<num2<<endl;
cout<<"Addition of the two numbers: "<< minInt + num2 <<endl;
cout<<endl;

system("pause");
return 0;
}

最佳答案

将 0x80000000 和 -21 相加得到 0x7FFFFFDF 的结果。这个十进制数是 2147483615。发生这种情况是因为最左边的位用于确定符号。你得到一个下溢,在这种情况下,它环绕到最大整数并从那里倒数。同样的事情应该以另一种方式发生,将两个正整数相加,除了它会环绕到 0,因为它是无符号的,但当你溢出或下溢时,它是未定义的行为。

正如评论所说,您可以使用更大的类型:

int64_t result = static_cast<int64_t>(maxInt) + num1;
int64_t result2 = static_cast<int64_t>(minInt) - num2;

关于c++ - 十六进制加减法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10670706/

相关文章:

javascript - 如何将一个十六进制数压缩成一个短字符串?

python - 在 Python 中将十六进制字符串转换为整数

c - 在十六进制中搜索特定字节

c++ - 使用/学习 VTK 和 C++ 的开发环境

c++ - 多次使用相同的 C++ 访问说明符

ios - Objective-c 负十六进制值

sql - 将 SQL 二进制内容转换为文件

c++ - 成员函数中的静态变量

C++/C 检测文件夹内容何时更改并通过 HTTP 发送文件的最佳方法

c++ - lambda 的捕获机制