Skip navigation

Monthly Archives: March 2010

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;
}