Click here to Skip to main content
14,935,907 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:

I want to convert the CString variable to unsigned char.
Can anyone help in this.

Here is my code,

CString strValue = "1";
unsigned char* cVal = (unsigned char*) (LPCTSTR) strValue;
varVal.bVal = *cVal;

If I execute the above code the value is displaying as "49"(varVal.bVal), but i want to display as "1".

Any help in this?
Updated 14-Oct-12 19:23pm
It's not nice to post code which won't even compile. What's "unsigend". It's a shame; you need to use Paste from copied real code.
Durga_Devi 15-Oct-12 1:23am
thanx. will modify the syntax
You are very welcome. Let's see... much better now :-)
I just fixed my answer where I messed up the links before -- sorry for the inconvenience.
Now the answer is ready -- please see.

First of all, you need to understand why you get 49. This is because this is the ASCII value of the character '1':[^].

The whole idea of "conversion" is wrong and manifest the lack of your understanding how data is represented in principle. To get what you want, you need to do something which is not related to "conversion"; this is "parsing". One of the functions you can use is this:[^].

This function needs a null-terminated string (as a char * pointer), which only looks like a typecast, but in fact this is a casting operator:[^].

CString strValue = "1";
unsigend char* cVal = (unsigned char *) strValue.GetBuffer(0);
The above can be modified as,
varVal.vt = VT_BSTR;
varVal.bstrVal = m_strValue.AllocSysString();

Now the varVal.bVal will have the value "1".
CString str = "sample";

char* c= str.getbuffer();

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900