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.
That is because the strtol returns long use this
unsigned long iMask = strtoul(pMaskBuffer, &p, 16);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With