Link to home
Start Free TrialLog in
Avatar of Nitro187
Nitro187

asked on

Convert a CString to an int.

You may be thinking "Just use atoi"... but that does not work in this case.  I am trying to convert a CString, "0x8b", to an int value of   0x8b  .    Here is some code that I have used:

char      Txt[3];
int      Val;
Txt = "0x8b";
if (strlen(Txt)==2)
{
      if (Txt[0]>='a') Txt[0]&=~0x20;
      if (Txt[1]>='a') Txt[1]&=~0x20;
      if (((Txt[0]>='0' && Txt[0]<='9') || (Txt[0]>='A' && Txt[0]<='F')) && ((Txt[1]>='0' && Txt[1]<='9') || (Txt[1]>='A' && Txt[1]<='F')))
      __asm {
            mov      ax,word ptr Txt
            sub      ax,0x3030
                  cmp      al,0x11
            setb      dl
            dec      dl
            and      dl,7
            sub      al,dl
                  cmp      ah,0x11
            setb      dl
            dec      dl
            and      dl,7
            sub      ah,dl
                  shl      al,4
            or            al,ah
            movzx      eax,al
            mov      Val,eax
      }
}


This is some code that a friend gave to me in order to do this.  It doesnt work in MFC though.  Is there another way to do this, that works?  Please help!
ASKER CERTIFIED SOLUTION
Avatar of paulburns
paulburns

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
Avatar of Vinayak Kumbar
Vinayak Kumbar

Hi,

Here is one way to do it.

CString str("0x123");
CString strTemp;
strTemp = str.Right(str.GetLength()-2);
int hexval = 0;
sscanf(strTemp, "%X", &hexval);

Now Ur hexval will contain the value of 0x123.

Try it out.
VinExpert
And it works for Ur case also.

VinExpert
You can just do this:

int val = 0;
CString text = "0x8b";
sscanf(text, "%x", &val);
Simply use the C Run-time library function _tcstoul (strtoul/wcstoul).

#include <tchar.h>
#include <stdlib.h>

LPTCSTR lpszStr = _T("0x8b");
LPTCSTR lpszStop;

unsigned long ulNum = _tcstoul(lpszStr, &lpszStop, 16);
CString str(_T("0x8b"));
LPTCSTR lpszStop;

long lNum = _tcstol(str, &lpszStop, 16);
Avatar of Nitro187

ASKER

Thanks a lot paul!
And thanks to everyone else who answered.  As for mnewton,  your answer was the same as his, but he answered first.  Thanks again.
That's fine. The reason I added a comment was to show it going from a CString instead of char *.