I have a function i VB.net which converts a string into the ascii hex version of the characters.

This functions looks like this in vb.net.

Code Snippet

Public Function StrToHex(ByVal str As String) As String

Dim stringPos As Integer

Dim strTemp As String

Dim strTemp2 As String

Dim strAnswer As String = String.Empty

stringPos = 1

Do While stringPos <= str.Length

strTemp = Mid$(str, stringPos, 1)

strTemp2 = CStr(Hex(Asc(strTemp)))

If Len(strTemp2) = 1 Then

strAnswer = strAnswer & "0" & strTemp2


strAnswer = strAnswer & strTemp2

End If

stringPos = stringPos + 1


StrToHex = strAnswer

End Function

So if send the string "3310 A" I get the result "333331302041" back.

My question is how do I accomplish this in C#

Many thanks in advance!

Re: Visual C# General string to hexadecimal string

Thomas Danecker

To convert a string to a byte-array which represents the ascii chars you can use

Code Snippet
[] bytes = System.Text.Encoding.ASCII.GetBytes(str);

When you have the bytes, you can easily convert them to a new string.

Re: Visual C# General string to hexadecimal string



That did the trick!