That is because the strtol returns long use this
unsigned long iMask = strtoul(pMaskBuffer, &p, 16);
Domanda
I am trying to do a conversion from hex string to integer in a MFC project. The code is like this:
CString sMask = "0xFFFFFFE0";
char* pMaskBuffer = sMask.GetBuffer(sMask.GetLength());
sMask.ReleaseBuffer();
char * p = NULL;
long iMask = strtol(pMaskBuffer, &p, 16);
The code was working fine when sMask variable was small.But 4 byte mask is generating strange values. Instead of 4294967264 , i am getting 2147483647. How to overcome this. Help please.
Soluzione
That is because the strtol returns long use this
unsigned long iMask = strtoul(pMaskBuffer, &p, 16);
Altri suggerimenti
Also make sure you ReleaseBuffer after use. You program has Undefined Behaviour
The address returned by GetBuffer is invalid after the call to ReleaseBuffer or any other CString operation.
http://msdn.microsoft.com/en-us/library/aa300574(v=vs.60).aspx
As people have explained, you want unsigned long
parsing.
From a std::strtol
reference page:
If the converted value falls out of range of corresponding return type, a range error occurs (setting
errno
toERANGE
) andLONG_MAX
,LONG_MIN
, ... is returned.
In your case LONG_MAX
is returned, and if you check errno
I'll bet it's going to be ERANGE
. The reason being that strtol
is for signed values, if you want unsigned values you should use std::strtoul
.
Also note, if you sometime in the future change to use the C++11 function std::stol
, it will throw an std::out_of_range
exception in this case.