Sunday, September 21, 2008

Converting Between String, ASCII, And Hex In .NET

Welcome again to my twisted mind. This post is just a quick example on converting between string, ascii and hexadecimal values using the .NET, specifically visual basic .NET programming.


Dim strOrig As String = "Hello"
Dim decimals As New List(Of Decimal)()
Dim hexStrs As New List(Of String)()
Dim intCurrent As Double

For Each c As Char In strOrig.ToCharArray()
intCurrent = Strings.Asc(c)
decimals.Add(intCurrent)
hexStrs.Add(Conversion.Hex(intCurrent))
Next

If hexStrs.Count > 0 Then
Console.Write("Hex: " & hexStrs(0))

For i As Integer = 1 To (hexStrs.Count - 1)
Console.Write(" " & hexStrs(i))
Next

Console.WriteLine("")
End If

If decimals.Count > 0 Then
Console.Write("Decimals: " & decimals(0))

For i As Integer = 1 To (decimals.Count - 1)
Console.Write(" " & decimals(i))
Next

Console.WriteLine("")
End If

Console.ReadLine()
As you can see above, .NET provides some nice conversion utilities for ascii value of a character and converting a decimal value to hexidecimal making the solution very straightforward as we just need to create a character array from string value and then convert each character to its ascii equivalent. Furthermore, we can quickly get the hexidecimal value for the character.


This is not rocket science by any stretch, but like posting things like this even as simple as it is so I for one don't forget it and to help another programmer get started on something more complex.


Anyway, for now that is it.


Happy programming.


References:

No comments: