convert ucs-2 to utf-8 in visual basic 2010

后端 未结 1 506
深忆病人
深忆病人 2021-01-27 14:07

Hello I used visual baisc 2010 and usb modem to sent at commands \" ussd \" by SerialPort \"AT+CUSD=1\" my problem when recive result get ucs-2 like this

<
相关标签:
1条回答
  • 2021-01-27 14:43

    It looks like that string, because of its composition, is in BigEndianUnicode format.
    This encoding format is available from .Net FW 3.5+ / VS 2008.
    The .Net version in use is more important than the Visual Studio version, though.

    So, let's try to parse this string and see what comes out of it.

    Dim input As String = [SerialPortOutput]
    
    input = input.Replace(ChrW(34), "")
    Dim ucs2 As String = input.Split(","c)(1)
    
    Dim HexBytes As List(Of Byte) = New List(Of Byte)()
    For i As Integer = 0 To ucs2.Length - 1 Step 2
        HexBytes.Add(Byte.Parse(ucs2.Substring(i, 2), NumberStyles.HexNumber))
    Next
    

    Now, transform the List of bytes from BigEndianUnicode to a standard .Net string.

    Dim output As String = Encoding.BigEndianUnicode.GetString(HexBytes.ToArray())
    

    The output string reads:

    "CurrentTime is: 21-JUL-2018 16:26"

    To convert it to UTF8, if really needed (Internet transfer, maybe), get the encoded array of bytes:

    Dim UTF8Bytes As Byte() = Encoding.UTF8.GetBytes(output)
    
    0 讨论(0)
提交回复
热议问题