十六进制加法和减法

时间:2012-05-20 04:03:41

标签: 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;
}

1 个答案:

答案 0 :(得分:8)

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

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

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