Home > ATL, MFC > How to convert ANSI string to UNICODE string and vice versa?

How to convert ANSI string to UNICODE string and vice versa?

Well quite simple,  but still quite frequently asked in forums… 🙂

There are two macros that does this for us. They are as follows.

Note: You must include atlconv.h

A2W – ANSI to UNICODE
W2A – UNICODE to ANSI

Before using these two macros you have to use this macro too…

USES_CONVERSION

Here is a code snippet for you… 😉

#include <atlconv .h>
//An example for converting from ANSI to UNICODE

//use this first
USES_CONVERSION;

//An ANSI string
LPSTR lpsz_ANSI_String = "An ANSI String";

//ANSI string being converted to a UNICODE string
LPWSTR lpUnicodeStr = A2W( lpsz_ANSI_String )

//Another example for converting from UNICODE to ANSI

//Use this first
USES_CONVERSION

//A UNICODE string
LPWSTR lp_UNICODE_STR = L"A Unicode String";

//UNICODE string being converted to a ANSI string
LPSTR  lpsz_ANSI_STR = W2A( lp_UNICODE_STR );

Another option is to call WideCharToMultiByte and MultiByteToWideChar directly, it’s quite easy to use, at least easier than above macros. If you have doubts on usage of above functions then take a look at AfxW2AHelper and AfxA2WHelper functions. Since these are the functions that A2W and W2A internally calls.

Also as a homework take a look at CW2AEX and CA2WEX classes. Will be similar to above macros, looks to me like a  secure version overload.

Advertisements
  1. erwin
    December 16, 2009 at 6:52 am

    its not working. I get compiler error.

  2. Ganesh Tiwari
    September 30, 2008 at 7:15 am

    Hello dear i am facing a problem with vb6.0 code i want to make node in tree view control in hindi but i dont have idea how to do one thing Unicode but how to apply this code in side the vb6.0 can any buddy suggest me please its urgent

  3. July 22, 2008 at 4:33 pm

    🙂 I am surprised, this has always worked for me! Can you show me your code snippet.

    Also remember don’t forget to add USES_CONVERSION above statements which use A2W and W2A. Also #include <atlconv.h> .

  4. Ryan
    July 22, 2008 at 1:23 pm

    Yeah, this code sample doesn’t work. You get compiler errors. The macros take use of some variables defined somewhere… god only knows where (course a simple search could find them if they actually exist).

  1. January 6, 2011 at 2:46 am
  2. September 5, 2008 at 1:30 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: