请教UCS2编码的字节数组如何转换转换成源来的数据?
C#技术
UCS2编码的字数组数据长度不限,字节数不固定(可能为4位,8位,10位,100位……),转换前肯定知道字节数组的长度。
请问如何转换?
#.Net 里面实现字符的编码和解码——
#region 生成字符(含英文)引用码
/// <summary>
/// 生成unicode实体引用的wap字符串,所有汉字均由此转换
/// </summary>
/// <param name="s_Chinese">中文字符串,可夹英文</param>
/// <returns></returns>
protected string Gen_Unicode(string s_Chinese)
{
string s_retu="";
char[] c_chars=s_Chinese.ToCharArray();
for(int i=0;i<c_chars.Length;i++)
{
s_retu+="" + ((short)c_chars[i]).ToString("X")+ ";";
}
return s_retu;
}
/// <summary>
/// 把 WAP 代码转换为字符(中文字符串,可夹英文)
/// </summary>
protected string Gen_Chinese(string s_Unicode)
{
string s_retu="";
string s1="";
string s2="";
byte[] array = new byte[2];
char []spar={';'};
string []chinese = s_Unicode.Split(spar);
int count=chinese.Length;
if(count>0)
{
for(int i=0;i<count;i++)
{
string s_tmp=chinese[i].Trim();
if(s_tmp!="")
{
// s_tmp=s_tmp.Substring(4);
if(s_tmp.Length>=4)
{
s1 = s_tmp.Substring(0,2);
s2 = s_tmp.Substring(2,2);
array[0] = (byte)Convert.ToInt32(s1,16);
array[1] = (byte)Convert.ToInt32(s2,16);
s_retu =s_retu + System.Text.Encoding.BigEndianUnicode.GetString(array);
}
else //英文的
{
// s1 = s_tmp.Substring(0,2);
s1 = "00";
s2 = s_tmp;
array[0] = (byte)Convert.ToInt32(s1,16);
array[1] = (byte)Convert.ToInt32(s2,16);
s_retu =s_retu + System.Text.Encoding.BigEndianUnicode.GetString(array);
}
}
}
}
return s_retu;
}
/// <summary>
/// 把字符转换为双字节的 hex
/// </summary>
/// <param name="s_Chinese">中文字符串,可夹英文</param>
protected string Gen_Hex(string s_Chinese)
{
string s_retu="";
char[] c_chars=s_Chinese.ToCharArray();
for(int i=0;i<c_chars.Length;i++)
{
string hex=((short)c_chars[i]).ToString("X");
if(hex.Length==2)//如果是单字节的则转换为双字节的字符
hex = "00" + hex;
s_retu+=hex;
}
return s_retu;
}
/// <summary>
/// 把 hex 代码转换为字符(中文字符串,可夹英文)
/// </summary>
protected string Gen_CharFromCode(string code)
{
string s = "";
for(int i=0;i<code.Length;i+=4)
{
string s1 = code.Substring(i,2);
string s2 = code.Substring(i+2,2);
int t1 = Convert.ToInt32(s1,16);
int t2 = Convert.ToInt32(s2,16);
byte[] array = new byte[2];
array[0] = (byte)t1;
array[1] = (byte)t2;
s += System.Text.Encoding.BigEndianUnicode.GetString(array);
}
return s;
}
#endregion