How to convert hex to string?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Mika M

    How to convert hex to string?

    Hi!

    I've made little code to convert string into hex string...

    Public ReadOnly Property ToHexString(ByV al text As String) As String
    Get
    Dim arrBytes As Integer() = CharsToBytes(te xt)
    Dim sb As StringBuilder = New StringBuilder

    For i As Integer = 0 To arrBytes.Length - 1
    '// If it's a single digit, append a zero in front of it.
    If (Hex(arrBytes(i )).Length = 1) Then
    sb.Append("0" + Hex(arrBytes(i) ))
    Else
    sb.Append(Hex(a rrBytes(i)))
    End If
    Next

    Return sb.ToString()
    End Get
    End Property

    Private Function CharsToBytes(By Val text As String) As Integer()
    Dim c As Char() = text.ToCharArra y()
    Dim arrBytes As Integer()
    ReDim arrBytes(c.Leng th() - 1)

    For i As Integer = 0 To c.Length() - 1
    arrBytes(i) = System.Convert. ToByte(c(i))
    Next

    Return arrBytes
    End Function

    .... and it's working fine. For example my name "MIKA" will be "4D494B41"
    as hex string, but I don't find out how to do this opposite way? I mean
    how to get "MIKA" of "4D494B41" hex string.

    Other question: It's possible to change when using VB like...

    Asc(c(i)) -> System.Convert. ToByte(c(i))

    .... is there also same kind of way for Hex()-function?

    --
    Thanks in advance!

    Mika
  • Oenone

    #2
    Re: How to convert hex to string?

    Mika M wrote:[color=blue]
    > ... and it's working fine. For example my name "MIKA" will be
    > "4D494B41" as hex string, but I don't find out how to do this
    > opposite way? I mean how to get "MIKA" of "4D494B41" hex string.[/color]

    Here's one way to do it:

    \\\
    Private Function DecodeHex(ByVal HexString As String) As String
    Dim thisChar As String
    Dim ascii As Integer
    Dim ret As String
    'Keep going until we exhaust all the source string
    Do While Len(HexString) > 0
    'Get the next two-digit hex number
    thisChar = HexString.Subst ring(0, 2)
    'Remove this hex number from the source string
    HexString = HexString.Subst ring(2)
    'Get the value in decimal of this hex number
    ascii = CInt(Val("&H" & thisChar))
    'Convert it to a character
    ret &= Chr(ascii)
    Loop
    'All done
    Return ret
    End Function
    ///

    Call this with "4D494B41" as the HexString parameter value and it will
    return "MIKA".

    It works by using a handy feature of the Val() command. If you pass a number
    prefixed with "&H", it will treat that as a hex number when it parses it. So
    if you ask it for Val("&H10"), it will return 16.

    The code simply loops through each pair of characters (each 8-bit hex value)
    and decodes the value to a number. It then gets the ASCII character
    represented by this number.

    There's no validation or anything so you'll need to add that yourself if
    there's a chance of passing non-hex values to the function.

    Hope that helps,

    --

    (O) e n o n e


    Comment

    • Crouchie1998

      #3
      Re: How to convert hex to string?

      Here's a shortened version of part of your existing code:

      You will notice that {0:X2} makes sure you always have 2 chars & you won't
      need to add your zero to the beginning

      Public Function ToHexString(ByV al sText As String) As String

      Dim arrBytes As Integer() = CharsToBytes(sT ext)
      Dim sb As StringBuilder = New StringBuilder

      For i As Integer = 0 To arrBytes.Length - 1
      sb.Append(Strin g.Format("{0:x2 }", Hex(arrBytes(i) )))
      Next

      Return sb.ToString()
      End Function

      Crouchie1998
      BA (HONS) MCP MCSE


      Comment

      • Crouchie1998

        #4
        Re: How to convert hex to string?

        Mika,

        I have created two functions of my own which will be better for you. The
        zipped project is also attached if you want to download it. Otherwise,
        follow thses instructions:

        1) Create a new Windows application
        2) Add a button
        3) Add this import:
        Imports System.text
        4) Now, paste in the following functions:

        Private Function EncodeHexString (ByVal sText As String) As String
        Dim intLength As Integer = sText.Length
        If (intLength = 0) Then Return ""
        Dim intCount As Integer = 0
        Dim sb As New StringBuilder(i ntLength * 2)
        Dim bBytes() As Byte = System.Text.Enc oding.ASCII.Get Bytes(sText)
        For intCount = 0 To bBytes.Length - 1
        sb.AppendFormat ("{0:X2}", bBytes(intCount ))
        Next
        Return sb.ToString()
        End Function

        Private Function DecodeHexString (ByVal sText As String) As String
        Dim intLength As Integer = sText.Length
        If (intLength = 0) Then Return ""
        Dim intCount As Integer = 0
        Dim sb As New StringBuilder(C Type(intLength / 2, Integer))
        Try
        For intCount = 0 To sText.Length - 1 Step 2
        sb.Append(Conve rt.ToChar(Byte. Parse(sText.Sub string(intCount ,
        2), Globalization.N umberStyles.Hex Number)))
        Next
        Catch ex As Exception
        Return ""
        End Try
        Return sb.ToString()
        End Function

        5) Double-click button1 & paste in this code:

        Dim strMika As String = "Mika"
        Dim strEncodedMika As String = EncodeHexString (strMika)
        MessageBox.Show (strEncodedMika )
        Dim strDecodedMika As String = DecodeHexString (strEncodedMika )
        MessageBox.Show (strDecodedMika )

        I hope this helps

        Crouchie1998
        BA (HONS) MCP MCSE


        Comment

        • Mika M

          #5
          Re: How to convert hex to string?

          Thank You Crouchie!!! Your code was easy to understand and very useful
          in my case!

          --
          Mika

          Comment

          • harry

            #6
            Re: How to convert hex to string?


            Not sure if this is the most elegent solution but if you still need one try
            this...

            Dim S as String = HexAsStringToCh aractersAsStrin g("4D494B41")

            S should now contain "MIKA"


            Private Function HexAsStringToCh aractersAsStrin g(ByVal HexString As String)
            As String

            'we`re assuming HexString passed is formatted as 2 chars for each
            individual Hex value
            'ie A = 0A, B=0B

            Dim UB As Integer = HexString.Lengt h - 1
            Dim SB As New StringBuilder

            For Idx As Integer = 0 To UB Step 2
            SB.Append(Micro soft.VisualBasi c.ChrW(System.C onvert.ToInt32( HexString.Chars (Idx)
            & HexString.Chars (Idx + 1), 16)))
            Next

            Return SB.ToString

            End Function



            "Mika M" <mahmik_nospam@ removethis_luuk ku.com> wrote in message
            news:O%23NBcd0O FHA.2384@tk2msf tngp13.phx.gbl. ..[color=blue]
            > Hi!
            >
            > I've made little code to convert string into hex string...
            >
            > Public ReadOnly Property ToHexString(ByV al text As String) As String
            > Get
            > Dim arrBytes As Integer() = CharsToBytes(te xt)
            > Dim sb As StringBuilder = New StringBuilder
            >
            > For i As Integer = 0 To arrBytes.Length - 1
            > '// If it's a single digit, append a zero in front of it.
            > If (Hex(arrBytes(i )).Length = 1) Then
            > sb.Append("0" + Hex(arrBytes(i) ))
            > Else
            > sb.Append(Hex(a rrBytes(i)))
            > End If
            > Next
            >
            > Return sb.ToString()
            > End Get
            > End Property
            >
            > Private Function CharsToBytes(By Val text As String) As Integer()
            > Dim c As Char() = text.ToCharArra y()
            > Dim arrBytes As Integer()
            > ReDim arrBytes(c.Leng th() - 1)
            >
            > For i As Integer = 0 To c.Length() - 1
            > arrBytes(i) = System.Convert. ToByte(c(i))
            > Next
            >
            > Return arrBytes
            > End Function
            >
            > ... and it's working fine. For example my name "MIKA" will be "4D494B41"
            > as hex string, but I don't find out how to do this opposite way? I mean
            > how to get "MIKA" of "4D494B41" hex string.
            >
            > Other question: It's possible to change when using VB like...
            >
            > Asc(c(i)) -> System.Convert. ToByte(c(i))
            >
            > ... is there also same kind of way for Hex()-function?
            >
            > --
            > Thanks in advance!
            >
            > Mika[/color]


            Comment

            Working...