Skip to content

Instantly share code, notes, and snippets.

@wolf99
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wolf99/c457a758329590ced577 to your computer and use it in GitHub Desktop.
Save wolf99/c457a758329590ced577 to your computer and use it in GitHub Desktop.
Extensions to convert VB.NET numeric type data to formatted hexadecimal strings
'Usage:
' Dim MyBytes() As Byte = {0, &HA5}
' Console.WriteLine(MyBytes.ToHexString)
' 'Prints "00 A5"
Imports System.Runtime.CompilerServices
Public Module Extensions
<Extension()>
Public Function ToHexString(a As Byte(), offset As Integer, length As Integer) As String
Dim RetVal As New System.Text.StringBuilder((length * 3) - 1)
Dim ByteStr As String
Dim Last As Integer = offset + length - 1
If BitConverter.IsLittleEndian Then
Array.Reverse(a)
End If
For i As Integer = offset To Last
ByteStr = New String(Conversion.Hex(a(i)))
If ByteStr.Length = 1 Then
RetVal.Append("0")
End If
RetVal.Append(ByteStr)
If i <> Last Then
RetVal.Append(" ")
End If
Next
Return RetVal.ToString
End Function
<Extension()>
Public Function ToHexString(a As Byte()) As String
Return a.ToHexString(0, a.Length)
End Function
<Extension()>
Public Function ToHexString(a As Byte) As String
Dim RetVal As New System.Text.StringBuilder(2)
Dim ByteStr As String = New String(Conversion.Hex(a))
If ByteStr.Length < 2 Then
RetVal.Append("0")
End If
RetVal.Append(ByteStr)
Return RetVal.ToString
End Function
<Extension()>
Public Function ToHexString(a As UInt16) As String
Return (BitConverter.GetBytes(a)).ToHexString
End Function
<Extension()>
Public Function ToHexString(a As UInt32) As String
Return (BitConverter.GetBytes(a)).ToHexString
End Function
<Extension()>
Public Function ToHexString(a As Int16) As String
Return (BitConverter.GetBytes(a)).ToHexString
End Function
<Extension()>
Public Function ToHexString(a As Int32) As String
Return (BitConverter.GetBytes(a)).ToHexString
End Function
End Module
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment