短信專用編碼格式轉換(如cmpp,sgip)

public enum CODING
{
ASCII=0,BINARY=4,UCS2=8,GBK=15
}
public static String Decode(Byte[] buf,int StartIndex,int Length,CODING Coding)
{
String str=String.Empty;
if(Coding==CODING.ASCII)
{
System.Text.ASCIIEncoding AsciiEncoder=new System.Text.ASCIIEncoding();
str=new String(AsciiEncoder.GetChars(buf,StartIndex,Length));
str=str.Split('/0')[0];

}
else if(Coding==CODING.UCS2)
{
Byte[] temp=new Byte[Length];
for(int i=0; i<Length;)
{
// 高低位字節對調
temp[i] =buf[StartIndex+i+1];
temp[i+1]= buf[StartIndex+i];
i=i+2;
}
System.Text.UnicodeEncoding UnicodeEncoder=new System.Text.UnicodeEncoding();
str=new String(UnicodeEncoder.GetChars(temp,0,Length));
str=str.Split('/0')[0];
}
else if(Coding==CODING.GBK)
{
System.Text.UnicodeEncoding Encoder=new System.Text.UnicodeEncoding();
System.Text.Encoding en=System.Text.UnicodeEncoding.GetEncoding("gb2312");
str=new String(en.GetChars(buf,StartIndex,Length));
str=str.Split('/0')[0];

}
return str;
}
public static Byte[] Encode(String str,CODING coding)
{
Byte[] buf=null;
if(coding==CODING.ASCII)
{
System.Text.ASCIIEncoding AsciiEncoder=new System.Text.ASCIIEncoding();
buf=AsciiEncoder.GetBytes(str);
}
else if(coding==CODING.UCS2)
{
System.Text.UnicodeEncoding UnicodeEncoder=new System.Text.UnicodeEncoding();
buf=UnicodeEncoder.GetBytes(str);
Byte temp=0;
for(int i=0; i<buf.Length;)
{
// 高低位字節對調
temp=buf[i] ;
buf[i]= buf[i+1];
buf[i+1]=temp;
i=i+2;
}
}
else if(coding==CODING.GBK)
{
System.Text.Encoding en=System.Text.UnicodeEncoding.GetEncoding("gb2312");
buf=en.GetBytes(str);
}

return buf;

}

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