Windows API Unicode 和 多字节转化demo

需要动态分配大小的得自己把转化封装一下,MinGW5下跑过.

test.c

#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <locale.h>
void print_hex(const UCHAR *buf, int len)
{
    int i;
    for (i = 0; i < len; i++) {
        printf("0x%02x ", *(buf + i));
        if (!((i + 1) % 4))
            printf("\t");
        if (!((i + 1) % 8))
            printf("\n");
    }
}
int main(int argc, char **argv)
{
    char buf[] = {
        0x41, 0x00, 0x42, 0x00,     0x43, 0x00, 0x44, 0x00,
        0x0d, 0x59, 0xf6, 0x4e,        0x00, 0x00
    };
    WCHAR *uStr = (WCHAR *)buf;
    int uLen, aLen;
    char *aStr, *locale;
    
    /* Set locale */
    locale = setlocale(LC_ALL, "");
    if(locale == NULL) 
        printf("Locale not set\n");
    else
        printf("Locale set to %s\n", locale);
        
    /* Print buf */
    wprintf(L"buf: %ws\n", buf);
    print_hex((UCHAR *)buf, 16);
    printf("\n");

    
    /* Unicode -> ANSI */
    aLen = WideCharToMultiByte(CP_ACP, 0, uStr, -1, NULL, 0, NULL, NULL);
    aStr = (char*) malloc(aLen);
    WideCharToMultiByte(CP_ACP, 0, uStr, -1, aStr, aLen, NULL, NULL);
    
    printf("aStr: %s\n", aStr);
    print_hex((UCHAR *)aStr, 16);
    printf("lstrlenA(aStr): %d\n", lstrlenA(aStr));
    printf("aLen: %d\n\n", aLen);
    
    
    /* ANSI -> Unicode */
    uLen = MultiByteToWideChar(CP_ACP, 0, aStr, -1, NULL, 0);
    uStr = (WCHAR *) malloc(uLen * sizeof(WCHAR));
    MultiByteToWideChar(CP_ACP, 0, aStr, -1, uStr, uLen);
    
    wprintf(L"uStr: %ws\n", uStr);
    print_hex((UCHAR *)uStr, 16);
    printf("lstrlenW(uStr): %d\n", lstrlenW(uStr));
    printf("uLen: %d\n\n", uLen);
        
    free(aStr);
    free(uStr);
    return EXIT_SUCCESS;
}

 

结果:

Locale set to Chinese (Simplified)_People's Republic of China.936
buf: ABCD复件
0x41 0x00 0x42 0x00     0x43 0x00 0x44 0x00
0x0d 0x59 0xf6 0x4e     0x00 0x00 0x40 0x00

aStr: ABCD复件
0x41 0x42 0x43 0x44     0xb8 0xb4 0xbc 0xfe
0x00 0x4c 0x4c 0x41     0x54 0x45 0x3d 0x43
lstrlenA(aStr): 8
aLen: 9

uStr: ABCD复件
0x41 0x00 0x42 0x00     0x43 0x00 0x44 0x00
0x0d 0x59 0xf6 0x4e     0x00 0x00 0x6f 0x70
lstrlenW(uStr): 6
uLen: 7

 

posted @ 2013-01-18 11:58  Leo Forest  阅读(384)  评论(0编辑  收藏  举报