本文共 1106 字,大约阅读时间需要 3 分钟。
最近用到SIM卡发短信,需要提取发送的数据,并将发送的数据转为Unicode码,因为利用PDU模式发送短信的时候,需要Unicode码才能发送。
对数据的转换需要了解,数据在linux下被存储为什么类型的码值,以及目前的码值转换为Unicode需要怎样处理。
Linux下的数据在内存里的存储是UTF8格式,所以转换为Unicode,就需要考虑怎样从UTF8转到Unicode码,利用下面的代码就可以得到Unicode码。
#include <stdio.h>
#include <string.h> #include <wchar.h> #include <locale.h> #include <stdlib.h> void toUnicode(wchar_t *pWstring, char *pResult) { for(unsigned int i = 0; i < wcslen(pWstring);++i) { sprintf(pResult,"%04X",pWstring[i]); pResult += 4; } } int main(int argc, char *argv[]) { if(!setlocale(LC_ALL,"zh_CN.UTF-8")) { printf("locale failed!\n"); return 1; } char dest[1024]; memset(dest,0x00,1024); strcpy(dest,"好好学习"); if(argc > 1) { memset(dest,0x00,1024); strcpy(dest,argv[1]); } wchar_t wbuf[256]; size_t rc = mbstowcs(wbuf,dest,sizeof(wbuf)/sizeof(wbuf[0]-1)); if(rc >= 0) { wbuf[rc] = L'\0'; memset(dest,0x00,1024); toUnicode(wbuf,dest); printf("dest is: %s\n",dest); } return 0; }最后打印出来的数据就是以Unicode码值显示出来,例如这里的结果,如果没有输入参数,就会打印“好好学习”的Unicode码:597D597D5B664E60。
在这里需要设置setlocale为UTF-8格式,才能正确的转换。
linux下的数据存储类型,可以参考链接:http://blog.csdn.net/lovekatherine/article/details/1868724