Skip navigation

Code to get a unicode string from an ascii string, and vice versa (ascii string from unicode)


wchar_t* GetUnicode( const char* asciiSrc )
{
  int alen = strlen( asciiSrc ) + 1;
  wchar_t* unicodeDest = (wchar_t*)malloc( alen*sizeof(wchar_t) );
  // MEASURE wlen
  int wlen = MultiByteToWideChar( CP_ACP, 0, asciiSrc, alen, 0, 0 ) ;
  // WRITE:
  MultiByteToWideChar( CP_ACP, 0, asciiSrc, alen, unicodeDest, wlen ) ;
  return unicodeDest;
}

char* GetAscii( const wchar_t* unicodeSrc )
{
  int wlen = wcslen( unicodeSrc ) + 1; // include null terminator in length of src
  // MEASURE ascii string's length
  int alen = WideCharToMultiByte( CP_ACP, 0, unicodeSrc, wlen, 0, 0, 0, 0 );
  char* asciiDest = (char*)malloc( alen*sizeof(char) );
  // WRITE the ascii string into asciiDest
  WideCharToMultiByte( CP_ACP, 0, unicodeSrc, wlen, asciiDest, alen, 0, 0 );
  return asciiDest;
}

string GetAscii( const wstring& unicode )
{
  char* ascii = GetAscii( unicode.c_str() );
  string copy( ascii );
  free( ascii );
  return copy;
}

wstring GetUnicode( const string& ascii )
{
  wchar_t* unicode = GetUnicode( ascii.c_str() );
  wstring copy( unicode );
  free( unicode );
  return copy;
}

Advertisements

One Trackback/Pingback

  1. By Unicode Usage in Video Games | DL-UAT on 08 Apr 2015 at 6:23 am

    […] I know it’s annoying, but I have this function […]

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: