Home All Groups Group Topic Archive Search About

How to convert hex to string?

Author
7 Apr 2005 7:56 AM
Mika M
Hi!

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

Public ReadOnly Property ToHexString(ByVal text As String) As String
   Get
     Dim arrBytes As Integer() = CharsToBytes(text)
     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(arrBytes(i)))
       End If
     Next

     Return sb.ToString()
   End Get
End Property

Private Function CharsToBytes(ByVal text As String) As Integer()
   Dim c As Char() = text.ToCharArray()
   Dim arrBytes As Integer()
   ReDim arrBytes(c.Length() - 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

Author
7 Apr 2005 9:52 AM
Oenone
Mika M wrote:
> ... 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.

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.Substring(0, 2)
            'Remove this hex number from the source string
            HexString = HexString.Substring(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
Author
7 Apr 2005 9:56 AM
Crouchie1998
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(ByVal sText As String) As String

Dim arrBytes As Integer() = CharsToBytes(sText)
Dim sb As StringBuilder = New StringBuilder

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

Return sb.ToString()
End Function

Crouchie1998
BA (HONS) MCP MCSE
Author
7 Apr 2005 10:22 AM
Crouchie1998
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(intLength * 2)
Dim bBytes() As Byte = System.Text.Encoding.ASCII.GetBytes(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(CType(intLength / 2, Integer))
Try
        For intCount = 0 To sText.Length - 1 Step 2
            sb.Append(Convert.ToChar(Byte.Parse(sText.Substring(intCount,
2), Globalization.NumberStyles.HexNumber)))
        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
Author
7 Apr 2005 10:25 AM
Crouchie1998
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(intLength * 2)
Dim bBytes() As Byte = System.Text.Encoding.ASCII.GetBytes(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(CType(intLength / 2, Integer))
Try
        For intCount = 0 To sText.Length - 1 Step 2
            sb.Append(Convert.ToChar(Byte.Parse(sText.Substring(intCount,
2), Globalization.NumberStyles.HexNumber)))
        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

[attached file: Mika's Solution.zip]
Author
7 Apr 2005 10:52 AM
Mika M
Thank You Crouchie!!! Your code was easy to understand and very useful
in my case!

--
Mika
Author
7 Apr 2005 11:10 AM
Crouchie1998
Pleasure

If you copy this code completely in & overwrite form1's code, you will have
a project I have created, which is better than the one attached previously.
Also, attached to this post:

'  ------------------------------
Imports System.text
Public Class Form1
Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
'Add any initialization after the InitializeComponent() call
End Sub
'Form overrides dispose to clean up the component list.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
Friend WithEvents btnCheck As System.Windows.Forms.Button
Friend WithEvents lblEntered As System.Windows.Forms.Label
Friend WithEvents txtEntered As System.Windows.Forms.TextBox
Friend WithEvents Label2 As System.Windows.Forms.Label
Friend WithEvents txtEncoded As System.Windows.Forms.TextBox
Friend WithEvents btnClear As System.Windows.Forms.Button
Friend WithEvents btnExit As System.Windows.Forms.Button
Friend WithEvents txtDecoded As System.Windows.Forms.TextBox
Friend WithEvents lblDecoded As System.Windows.Forms.Label
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Me.btnCheck = New System.Windows.Forms.Button
Me.lblEntered = New System.Windows.Forms.Label
Me.txtEntered = New System.Windows.Forms.TextBox
Me.Label2 = New System.Windows.Forms.Label
Me.txtEncoded = New System.Windows.Forms.TextBox
Me.btnClear = New System.Windows.Forms.Button
Me.btnExit = New System.Windows.Forms.Button
Me.txtDecoded = New System.Windows.Forms.TextBox
Me.lblDecoded = New System.Windows.Forms.Label
Me.SuspendLayout()
'
'btnCheck
'
Me.btnCheck.Location = New System.Drawing.Point(16, 152)
Me.btnCheck.Name = "btnCheck"
Me.btnCheck.TabIndex = 0
Me.btnCheck.Text = "Check"
'
'lblEntered
'
Me.lblEntered.Location = New System.Drawing.Point(16, 8)
Me.lblEntered.Name = "lblEntered"
Me.lblEntered.Size = New System.Drawing.Size(100, 16)
Me.lblEntered.TabIndex = 1
Me.lblEntered.Text = "Entered Text:"
'
'txtEntered
'
Me.txtEntered.Location = New System.Drawing.Point(16, 24)
Me.txtEntered.Name = "txtEntered"
Me.txtEntered.Size = New System.Drawing.Size(248, 20)
Me.txtEntered.TabIndex = 2
Me.txtEntered.Text = ""
'
'Label2
'
Me.Label2.Location = New System.Drawing.Point(16, 56)
Me.Label2.Name = "Label2"
Me.Label2.Size = New System.Drawing.Size(100, 16)
Me.Label2.TabIndex = 3
Me.Label2.Text = "Encoded:"
'
'txtEncoded
'
Me.txtEncoded.BackColor = System.Drawing.SystemColors.HighlightText
Me.txtEncoded.Location = New System.Drawing.Point(16, 72)
Me.txtEncoded.Name = "txtEncoded"
Me.txtEncoded.ReadOnly = True
Me.txtEncoded.Size = New System.Drawing.Size(248, 20)
Me.txtEncoded.TabIndex = 4
Me.txtEncoded.Text = ""
'
'btnClear
'
Me.btnClear.Location = New System.Drawing.Point(104, 152)
Me.btnClear.Name = "btnClear"
Me.btnClear.TabIndex = 5
Me.btnClear.Text = "Clear"
'
'btnExit
'
Me.btnExit.Location = New System.Drawing.Point(192, 152)
Me.btnExit.Name = "btnExit"
Me.btnExit.TabIndex = 6
Me.btnExit.Text = "Exit"
'
'txtDecoded
'
Me.txtDecoded.BackColor = System.Drawing.SystemColors.HighlightText
Me.txtDecoded.Location = New System.Drawing.Point(16, 120)
Me.txtDecoded.Name = "txtDecoded"
Me.txtDecoded.ReadOnly = True
Me.txtDecoded.Size = New System.Drawing.Size(248, 20)
Me.txtDecoded.TabIndex = 7
Me.txtDecoded.Text = ""
'
'lblDecoded
'
Me.lblDecoded.Location = New System.Drawing.Point(16, 104)
Me.lblDecoded.Name = "lblDecoded"
Me.lblDecoded.Size = New System.Drawing.Size(100, 16)
Me.lblDecoded.TabIndex = 8
Me.lblDecoded.Text = "Decoded:"
'
'Form1
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(280, 183)
Me.Controls.Add(Me.lblDecoded)
Me.Controls.Add(Me.txtDecoded)
Me.Controls.Add(Me.btnExit)
Me.Controls.Add(Me.btnClear)
Me.Controls.Add(Me.txtEncoded)
Me.Controls.Add(Me.Label2)
Me.Controls.Add(Me.txtEntered)
Me.Controls.Add(Me.lblEntered)
Me.Controls.Add(Me.btnCheck)
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle
Me.MaximizeBox = False
Me.Name = "Form1"
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
Me.Text = "Encode/Decode Hex String"
Me.ResumeLayout(False)
End Sub
#End Region
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(intLength * 2)
Dim bBytes() As Byte = System.Text.Encoding.ASCII.GetBytes(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(CType(intLength / 2, Integer))
Try
For intCount = 0 To sText.Length - 1 Step 2
sb.Append(Convert.ToChar(Byte.Parse(sText.Substring(intCount, 2),
Globalization.NumberStyles.HexNumber)))
Next
Catch ex As Exception
Return ""
End Try
Return sb.ToString()
End Function
Private Sub btnCheck_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnCheck.Click
If txtEntered.Text.Trim = "" Then
MessageBox.Show("Please enter some text", Me.Text)
txtEntered.Text = ""
txtEntered.Focus()
Exit Sub
End If
txtEncoded.Text = EncodeHexString(txtEntered.Text)
txtDecoded.Text = DecodeHexString(txtEncoded.Text)
End Sub
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnClear.Click
txtEntered.Text = ""
txtEncoded.Text = ""
txtDecoded.Text = ""
txtEntered.Focus()
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnExit.Click
Application.Exit()
End Sub
End Class
' ---------------

The above will save you a little work I think

Crouchie1998
BA (HONS) MCP MCSE

[attached file: Encode And Decode Hex.zip]
Author
10 Apr 2005 10:12 AM
harry
Not sure if this is the most elegent solution but if you still need one try
this...

Dim S as String = HexAsStringToCharactersAsString("4D494B41")

S should now contain "MIKA"


Private Function HexAsStringToCharactersAsString(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.Length - 1
        Dim SB As New StringBuilder

        For Idx As Integer = 0 To UB Step 2
            SB.Append(Microsoft.VisualBasic.ChrW(System.Convert.ToInt32(HexString.Chars(Idx)
& HexString.Chars(Idx + 1), 16)))
        Next

        Return SB.ToString

    End Function



Show quoteHide quote
"Mika M" <mahmik_nospam@removethis_luukku.com> wrote in message
news:O%23NBcd0OFHA.2384@tk2msftngp13.phx.gbl...
> Hi!
>
> I've made little code to convert string into hex string...
>
> Public ReadOnly Property ToHexString(ByVal text As String) As String
>   Get
>     Dim arrBytes As Integer() = CharsToBytes(text)
>     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(arrBytes(i)))
>       End If
>     Next
>
>     Return sb.ToString()
>   End Get
> End Property
>
> Private Function CharsToBytes(ByVal text As String) As Integer()
>   Dim c As Char() = text.ToCharArray()
>   Dim arrBytes As Integer()
>   ReDim arrBytes(c.Length() - 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