Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / VB

Convert a string to UTF-16

3.67/5 (3 votes)
28 Mar 2010CPOL 1  
This Function allows you to convert a normal string to UTF-16 encoding in VB.NET. You can find tools like Unicode Code Converter that operate like ConvertToUTF16 function.' if you pass this parameter to function : I'm from Azerbaijan.' the return value is :...
This Function allows you to convert a normal string to UTF-16 encoding in VB.NET. You can find tools like Unicode Code Converter that operate like ConvertToUTF16 function.

' if you pass this parameter to function : "I'm from Azerbaijan."
' the return value is : 00490027006D002000660072006F006D00200041007A00650072006200610069006A0061006E002E that is Hexadecimal code points of the input string.
' UTF-16 code units is like this: 49 27 6D 20 66 72 6F 6D 20 41 7A 65 72 62 61 69 6A 61 6E 2E

Public Function ConvertToUTF16(ByVal str As String) As String
Dim ArrayOFBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(str)
        Dim UTF16 As String
        Dim v As Integer
        For v = 0 To ArrayOFBytes.Length - 1
            If v Mod 2 = 0 Then
                Dim t As Integer = ArrayOFBytes(v)
                ArrayOFBytes(v) = ArrayOFBytes(v + 1)
                ArrayOFBytes(v + 1) = t
            End If
        Next
        For v = 0 To ArrayOFBytes.Length - 1
            Dim c As String = Hex$(ArrayOFBytes(v))
            If c.Length = 1 Then
                c = "0" & c
            End If
            UTF16 = UTF16 & c
        Next

        Return UTF16
End Function

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)