How to convert hex to string?

M

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?
 
O

Oenone

Mika said:
... 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,
 
C

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
 
C

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
 
M

Mika M

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

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top