Share via


Convert CString to DWORD

Question

Friday, October 31, 2014 12:35 PM

I have follow CString:

CString sTemp(_T("20120827114308"));

and I want to convert to DWORD ... and I had tried in foloow way:

DWORD dwBuffer = (DWORD)sTemp.GetBuffer(sTemp.GetLength());

but result is:

5787108

why ?

All replies (6)

Friday, October 31, 2014 2:17 PM âś…Answered

Now I am searching CString to unsigned int64 ... but as I am using VC6, I don't have so much possibilities ...

I believe VC6 supports __int64 and unsigned __int64, and also _atoi64.

David Wilkinson | Visual C++ MVP


Friday, October 31, 2014 1:09 PM

I have follow CString:

CString sTemp(_T("20120827114308"));

and I want to convert to DWORD ... and I had tried in foloow way:

DWORD dwBuffer = (DWORD)sTemp.GetBuffer(sTemp.GetLength());

but result is:

5787108

why ?

What do expect to happen? What is the purpose of this conversion?

CString::GetBuffer() returns a TCHAR* pointer to a nul-terminated string, so the DWORD conversion is just the value of the address.

If you want to treat the value 20120827114308 as a DWORD you should realize that this value is too big to fit in a DWORD (which is unsigned int -- 32 bits).

David Wilkinson | Visual C++ MVP


Friday, October 31, 2014 1:33 PM

I tried this too:

DWORD dwBuffer = _tcstoul(sTemp, 0, 10);

result: -1.


Friday, October 31, 2014 1:41 PM

I tried this too:

DWORD dwBuffer = _tcstoul(sTemp, 0, 10);

result: -1.

From the documentation

strtoul returns the converted value, if any, or ULONG_MAX on overflow

On Windows, ULONG_MAX is hexadecimal 0xFFFFFFFF, which is -1 if viewed as a signed integer.

As I told you, 20120827114308 is too big to fit in a 32-bit integer (either signed or unsigned). You need a 64-bit type to hold this value.

David Wilkinson | Visual C++ MVP


Friday, October 31, 2014 1:53 PM

Now I am searching CString to unsigned int64 ... but as I am using VC6, I don't have so much possibilities ...


Monday, November 3, 2014 8:47 AM

I solved in this way:

   unsigned __int64 ui64;
    _stscanf((LPCTSTR)sTemp, _T("%I64u"), &ui64);