UCS2编码也就是两字节的Unicode编码,Unicode编码除了UCS2外还有UCS4规范,VB.Net中将汉字转换成UCS2编码方法很简单,可以直接调用System.Text.Encoding.Unicode.GetBytes方法就可以实现,比如System.Text.Encoding.Unicode.GetBytes(“程”)就可以得到“程”的UCS2编码0B 7A,不过在PDU中UCS2编码的字节顺序和这样取到字节顺序是相反的,PDU的顺序是7A0B,因此还需要将System.Text.Encoding.Unicode.GetBytes取到的字节位置进行一下交换。具体代码如下:
'UCS2编码 Public Function Encoder_UCS2(ByVal s As String) As Byte() '取Unicode编码Byte数组 Dim arr() As Byte = System.Text.Encoding.Unicode.GetBytes(s) Dim tmp As Byte '换位 For xx As Integer = 0 To arr.Length - 2 Step 2 tmp = arr(xx) arr(xx) = arr(xx + 1) arr(xx + 1) = tmp Next Encoder_UCS2 = arr Erase arr End Function 'UCS2解码 Public Function Decoder_UCS2(ByVal s As Byte()) As String Dim tmp As Byte '换位 For xx As Integer = 0 To s.Length - 2 Step 2 tmp = s(xx) s(xx) = s(xx + 1) s(xx + 1) = tmp Next Decoder_UCS2 = System.Text.Encoding.Unicode.GetString(s) End Function原文链接:https://www.f2er.com/vb/257552.html