編碼轉換問題

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iconv.h>
/**
 * 中文字串轉爲utf8格式字串
 * src  中文字串
 * ret  utf8字串
 * len  src串的長度
 * 返回轉換後的utf8串的長度
 * 說明:ret大小應該是src的1.5倍以上。一個漢字轉爲了3個字節的utf編碼
 **/
int To_utf8(unsigned char *src,unsigned char *ret,int len){
	iconv_t c_p;
	char *in,*out;
	int i,i_len,o_len;
	unsigned char tmp[1500];
	memset(tmp,0,sizeof(tmp));
	c_p=iconv_open("UTF-8","GBK"); //GBK 轉爲 UTF-8
	in=(char *)src;out=(char *)tmp;
	i_len=len;o_len=1500;
	iconv(c_p,&in,(size_t*)&i_len,&out,(size_t*)&o_len);
	i=strlen((char *)tmp);
	memcpy(ret,tmp,i);
	iconv_close(c_p);
	return i;
}
 
/**
 * utf8格式字串轉爲中文字串
 * src  utf8字串
 * ret  中文字串
 * len  src串的長度
 * 返回轉換後的中文串的長度
 **/
int To_gbk(unsigned char *src,unsigned char *ret,int len){
	iconv_t c_p;
	char *in,*out;
	int i,i_len,o_len;
	unsigned char tmp[1500];
	memset(tmp,0,sizeof(tmp));
	c_p=iconv_open("GBK","UTF-8"); //UTF-8轉爲 GBK 
	in=(char *)src;out=(char *)tmp;
	i_len=len;o_len=1500;
	iconv(c_p,&in,(size_t*)&i_len,&out,(size_t*)&o_len);
	i=strlen((char *)tmp);
	memcpy(ret,tmp,i);
	iconv_close(c_p);
	return i;
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章