Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting 4byte hex string to integer

Tags:

c++

hex

mfc

strtol

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.

like image 416
Codename_DJ Avatar asked Nov 25 '25 02:11

Codename_DJ


2 Answers

That is because the strtol returns long use this

unsigned long iMask = strtoul(pMaskBuffer, &p, 16);
like image 185
kunal Avatar answered Nov 26 '25 15:11

kunal


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.

like image 22
sehe Avatar answered Nov 26 '25 15:11

sehe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!