Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
883 views
in Technique[技术] by (71.8m points)

c# - Convert to UCS2

Is there any function in Vb.net (or C#) that encodes a string in UCS2?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the following functions to encode unicode string in "UCS2" format:

    //================> Used to encoding GSM message as UCS2
    public static String UnicodeStr2HexStr(String strMessage)
    {
        byte[] ba = Encoding.BigEndianUnicode.GetBytes(strMessage);
        String strHex = BitConverter.ToString(ba);
        strHex = strHex.Replace("-", "");
        return strHex;
    }

    public static String HexStr2UnicodeStr(String strHex)
    {
        byte[] ba = HexStr2HexBytes(strHex);
        return HexBytes2UnicodeStr(ba);
    }

    //================> Used to decoding GSM UCS2 message  
    public static String HexBytes2UnicodeStr(byte[] ba)
    {
        var strMessage = Encoding.BigEndianUnicode.GetString(ba, 0, ba.Length);
        return strMessage;
    }

    public static byte[] HexStr2HexBytes(String strHex)
    {
        strHex = strHex.Replace(" ", "");
        int nNumberChars = strHex.Length / 2;
        byte[] aBytes = new byte[nNumberChars];
        using (var sr = new StringReader(strHex))
        {
            for (int i = 0; i < nNumberChars; i++)
                aBytes[i] = Convert.ToByte(new String(new char[2] { (char)sr.Read(), (char)sr.Read() }), 16);
        }
        return aBytes;
    }

for example:

String strE = SmsEngine.UnicodeStr2HexStr("???? ?? ???? ?????");
// strE = "0633064406270645002006280647002006AF0686067E06980020067E062706310633064A"
String strD = SmsEngine.HexStr2UnicodeStr("0633064406270645002006280647002006AF0686067E06980020067E062706310633064A");
// strD = "???? ?? ???? ?????"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...