'将整数转换为byte数组:
Public Function ToBytes(ByVal v As Integer) As Byte()
Dim b(-1) As Byte
Do
ReDim Preserve b(b.Length)
b(b.Length - 1) = v Mod 256
v = v / 256
Loop While v >= 1
If b.Length Mod 2 = 1 Then
ReDim Preserve b(b.Length)
b(b.Length - 1) = 0
End If
Return b
End Function
'得到Unicode字符
dim Result as string = Encoding.Unicode.GetString(ToBytes(Value))
[Visual Basic]
Imports System
Imports System.IO
Imports System.Globalization
Imports System.Text
Public Class Encoding_UnicodeToCP
Public Shared Sub Main()
' Converts ASCII characters to bytes.
' Displays the string's byte representation in the
' specified code page.
' Code page 1252 represents Latin characters.
PrintCPBytes("Hello, World!", 1252)
' Code page 932 represents Japanese characters.
PrintCPBytes("Hello, World!", 932)
' Converts Japanese characters.
PrintCPBytes("\u307b,\u308b,\u305a,\u3042,\u306d",1252)
PrintCPBytes("\u307b,\u308b,\u305a,\u3042,\u306d",932)
End Sub
Public Shared Sub PrintCPBytes(str As String, codePage As Integer)
Dim targetEncoding As Encoding
Dim encodedChars() As Byte
' Gets the encoding for the specified code page.
targetEncoding = Encoding.GetEncoding(codePage)
' Gets the byte representation of the specified string.
encodedChars = targetEncoding.GetBytes(str)
' Prints the bytes.
Console.WriteLine("Byte representation of '{0}' in CP '{1}':", _
str, codePage)
Dim i As Integer
For i = 0 To encodedChars.Length - 1
Console.WriteLine("Byte {0}: {1}", i, encodedChars(i))
Next i
End Sub
End Class