Thursday, April 8, 2010

[vb.net] To convert a unicode character to Hexadecimal

Imports System
Imports System.Text
Imports Microsoft.VisualBasic.Strings

Class UnicodeToHex
   'The encoding
   Dim uni As New UnicodeEncoding()

   Public Shared Sub Main()     

        Dim str As String = "म" 'unicode string
       
        Dim byteArray() As Byte
        byteArray = uni.GetBytes(str)
        str = GetAsHexaDecimal(byteArray)
        
        'Show the message
        MessageBox.Show(str)
    End Sub

    Public Function GetAsHexaDecimal(ByVal bytes As Byte()) As String
        Try
            Dim s As New StringBuilder
            Dim length, n As Integer
            length = bytes.Length
            For n = length - 1 To 0 Step -1
                s.Append(String.Format("{0,2:x}", bytes(n)).Replace(" ", "0"))
            Next
            Return s.ToString

        Catch ex As Exception

        End Try
    End Function
End Class

No comments:

Post a Comment