Convert Unicode To UTF8

char* __stdcall UnicodeToUtf8( const WCHAR* wstr )
{
    const WCHAR* w;
    // Convert unicode to utf8
    int len = 0;
    for ( w = wstr; *w; w++ ) { 
         if ( *w < 0×0080 ) len++;
        else if ( *w < 0×0800 ) len += 2;
        else len += 3;
    }
    unsigned char* szOut = ( unsigned char* )malloc( len+1 );
    if ( szOut == NULL )
        return NULL;
    int i = 0;
    for ( w = wstr; *w; w++ ) {
        if ( *w < 0×0080 )
            szOut[i++] = ( unsigned char ) *w;
        else if ( *w < 0×0800 ) {
            szOut[i++] = 0xc0 | (( *w ) >> 6 );
            szOut[i++] = 0×80 | (( *w ) & 0×3f );
        }
        else {
            szOut[i++] = 0xe0 | (( *w ) >> 12 );
            szOut[i++] = 0×80 | (( ( *w ) >> 6 ) & 0×3f );
            szOut[i++] = 0×80 | (( *w ) & 0×3f );
        }
    }
    szOut[ i ] = ‘‘;
    return ( char* )szOut;
}

发表评论