[VB.NET]ASCII String與Hex String的互轉
Public Function AsciiStringToHexString(ByVal asciiString As String) As String
Dim ascii() As Byte = System.Text.Encoding.Default.GetBytes(asciiString)
Dim count As Integer = ascii.Length
Dim hexArray(count - 1) As String
For idx As Integer = 0 To count - 1
hexArray(idx) = ascii(idx).ToString("x2")
Next
Return String.Join(" ", hexArray)
End Function
Public Function HexStringToAsciiString(ByVal hexString As String) As String
Dim array() As String = hexString.Split(New Char() {" "c}, StringSplitOptions.RemoveEmptyEntries)
For idx As Integer = 0 To array.Length - 1
array(idx) = Chr(CInt(String.Format("&h{0}", array(idx))))
Next
Return String.Join(String.Empty, array)
End Function
Private Sub tbxASCII_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbxASCII.TextChanged
If Me.ActiveControl Is sender Then
tbxHex.Text = AsciiStringToHexString(tbxASCII.Text)
End If
End Sub
Private Sub tbxHex_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbxHex.TextChanged
If Me.ActiveControl Is sender Then
tbxASCII.Text = HexStringToAsciiString(tbxHex.Text)
End If
End Sub
End Class