Click here to Skip to main content
15,885,979 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi,

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

Here is my code,

C++
VARIANT varVal;
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?
Posted
Updated 14-Oct-12 19:23pm
v3
Comments
Sergey Alexandrovich Kryukov 15-Oct-12 1:21am    
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.
--SA
Durga_Devi 15-Oct-12 1:23am    
thanx. will modify the syntax
Sergey Alexandrovich Kryukov 15-Oct-12 1:35am    
You are very welcome. Let's see... much better now :-)
--SA
Sergey Alexandrovich Kryukov 15-Oct-12 1:37am    
I just fixed my answer where I messed up the links before -- sorry for the inconvenience.
Now the answer is ready -- please see.
--SA

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

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:
http://www.cplusplus.com/reference/clibrary/cstdlib/atoi[^].

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:
http://msdn.microsoft.com/en-us/library/aa300569%28v=vs.60%29.aspx[^].

—SA
 
Share this answer
 
v3
CString strValue = "1";
unsigend char* cVal = (unsigned char *) strValue.GetBuffer(0);
 
Share this answer
 
Comments
Nikita Vedre 29-Jun-21 8:16am    
It still give same error
The above can be modified as,
C++
varVal.vt = VT_BSTR;
varVal.bstrVal = m_strValue.AllocSysString();
VariantChangeType(&varVal,&varVal,0,VT_UI1);


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

char* c= str.getbuffer();
str.releasebuffer();
 
Share this answer
 

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