converting hex to int

i need to convert a negative hex value to an integer.

could somebody please explain to me why when i am convert FFFFEFFFE.
it produces 4294901758.
but when i use the f = x it gives me the correct value which is -65538.
thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include "stdafx.h"
#include <sstream>
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	stringstream ss;
	ss << hex << "FFFEFFFE";
	unsigned int x; 
	long int f;
	ss >> x;
	std::cout << x << std::endl;
	// 4294901758
	f = x;
	// -65538
	std::cout << f << std::endl;
	
	int z;
	cin >> z;
	return 0;
}
Both 4294901758 and -65538 are correct, depending on whether the value is interpreted as a signed or unsigned 32-bit number.
1
2
3
4
5
    unsigned long a = 0xFFFEFFFE;
    long b          = 0xFFFEFFFE;
    
    cout << a << endl;
    cout << b << endl;
4294901758
-65538

Topic archived. No new replies allowed.