472,114 Members | 1,480 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,114 software developers and data experts.

C++: Convert unsigned char to CString and char *

It is a C++ questions:
How to Convert unsigned char to CString and char *; and backward as well?
Jan 12 '07 #1
3 33240
Banfa
9,065 Expert Mod 8TB
unsigned char to char * is fairly simple

Expand|Select|Wrap|Line Numbers
  1. unsigned char uc = 'A';
  2.  
  3. char *p = (char *)&uc;
  4.  
  5. /* and back */
  6.  
  7. uc = *p;  /* this may produce a warning that can be removed with a cast */
  8.  
The cast is needed because you are loosing the unsigned qualifier. Of course this does not give you a pointer to a c string because a c string requires zero termination there for a single character requires an array of at least 2 characters so that the zero terminator can be included.


unsigned char to CString is a little more problematic, I can't remember if you can just assign a char to a CString, if so no problem. If not the easiest way is probably to clear the CString and add (+) the unsigned char probably casting it first.


Expand|Select|Wrap|Line Numbers
  1. unsigned char uc ='A';
  2.  
  3. CString str;
  4.  
  5. str = (char)uc;  /* Not sure if this works */
  6.  
  7. str = "";          /* fairly sure this will work */
  8. str += (char)uc;
  9.  
  10. /* and back */
  11.  
  12. uc = str[0];  /* Extract the first character of str */
  13.  
Jan 13 '07 #2
Banfa
9,065 Expert Mod 8TB
I just checked you can construct a CString from an unsigned char like this

Expand|Select|Wrap|Line Numbers
  1. unsigned char uc = 'A';
  2.  
  3. CString str((char)uc);
  4.  
Jan 13 '07 #3
Thank you all very much!
Jan 16 '07 #4

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

30 posts views Thread by Tim Johansson | last post: by
4 posts views Thread by ravinderthakur | last post: by
15 posts views Thread by Yifan | last post: by
3 posts views Thread by QQ | last post: by
8 posts views Thread by AGRAJA | last post: by
reply views Thread by leo001 | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.