Link to home
Start Free TrialLog in
Avatar of mr_stevie
mr_stevieFlag for Australia

asked on

Converting a Hex CString to Decimal CString

Hello.

I know there are many resources available for this question but they all don't seem to work for me for some reason.

I am trying to convert a CString representing a hex number into a CString containing a decimal number.

For example:

CString hexstring = 07BE;
CString decimalstring;

I want to convert 07BE to 1982.

If anyone can help, will be greatly appreciated!

Thank you in advance.
Avatar of jkr
jkr
Flag of Germany image

The easiest way would probably be 'strtol()' (or '_tcstol()' respectively) along with 'CString::Format()' then, e.g.
#include <stdlib.h>

//...

CString HexStrToDecStr(const CString& sHex) {

  CString sDec;
  char *p;
  sDec.Format("%d",_tcstol(sHex,&p,16));

  return sDec;
}

Open in new window

Avatar of mr_stevie

ASKER

Unfortunately, i get the follow errors:

For strtol():

Error      1      error C2664: 'strtol' : cannot convert parameter 1 from 'CString' to 'const char *'      
Error      2      error C2664: 'void ATL::CStringT<BaseType,StringTraits>::Format(const wchar_t *,...)' : cannot convert parameter 1 from 'const char [3]' to 'const wchar_t *'



For_tcstol():

Error      3      error C2664: 'wcstol' : cannot convert parameter 2 from 'char **__w64 ' to 'wchar_t **'
Error      4      error C2664: 'void ATL::CStringT<BaseType,StringTraits>::Format(const wchar_t *,...)' : cannot convert parameter 1 from 'const char [3]' to 'const wchar_t *'
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Unfortunately, that still gives me problems.

However, I think I've managed to figure it out.

For some reason, char* isn't working properly and I'm using a wchar_t*.

Also,  "%d" needs to be _T("%d") to convert to UNICODE.

Otherwise, the following code seems works fine!

Thank you very much!
wchar_t *p;
sDec.Format( _T("%d") , _tcstol( sHex, &p, 16 ) );

Open in new window