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


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


Here is a code snippet for you… 😉

[sourcecode language=’cpp’]#include
//An example for converting from ANSI to UNICODE

//use this first

//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

//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 );[/sourcecode]

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.

6 thoughts on “How to convert ANSI string to UNICODE string and vice versa?

  1. 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).

  2. 🙂 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> .

  3. 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

Appreciate your comments...