user1251302
user1251302

Reputation: 91

Hexadecimals adding and subtracting

I have this code so far. When I add the two negative integers, the answer is positive instead of negative. How do I fix this? I think the 0x80000000 is the smallest possible value for a integer

#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;
}

Upvotes: 2

Views: 2696

Answers (1)

Qaz
Qaz

Reputation: 61900

Adding 0x80000000 and -21 gives a result of 0x7FFFFFDF. This number in decimal is 2147483615. This happens because the leftmost bit is used to determine the sign. You're getting an underflow, which in this case wraps around to the maximum integer and counts down from there. The same thing should be happening the other way with adding the two positive integers, except that it would wrap around to 0 as it's unsigned, but it is undefined behaviour when you overflow or underflow.

As the comments say, you could use a bigger type:

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

Upvotes: 7

Related Questions