Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleWrite extension methods to convert between byte arrays and strings of hexadecimal values in Visual Basic .NET
DescriptionThis example shows how to write extension methods to convert between byte arrays and strings of hexadecimal values in Visual Basic .NET.
Keywordsstrings, variables, string extension, extensions, extension methods, Visual Basic, Visual Basic .NET, VB.NET
CategoriesSoftware Engineering, Tips and Tricks
 
An extension method is a method that you add to an existing data type. This example adds a ToHex method to the byte array type and a ToBytes method to the string class.

To create an extension method, decorate the method with the Extension attributes. The method's first parameter determines the type to which the method applies.

The following code shows the byte array type's new ToHex method. Notice how the first parameter has the "this" keyword and has type byte[].

 
' Return a string that represents the byte array
' as a series of hexadecimal values, optionally
' separated by spaces.
<Extension()> _
Public Function ToHex(ByVal the_bytes() As Byte, Optional _
    ByVal add_spaces As Boolean = False) As String
    Dim result As String = ""
    Dim separator As String = ""
    If (add_spaces) Then separator = " "
    For i As Integer = 0 To the_bytes.Length - 1
        result &= the_bytes(i).ToString("x2") & separator
    Next i
    Return result
End Function
 
The ToHex method loops through the array's bytes adding 2-digit hexadecimal representations of each to the result string.

The following code shows the string class's new ToBytes method.

 
' Convert a string containing 2-digit hexadecimal values
' into a byte array.
<Extension()> _
Public Function ToBytes(ByVal the_string As String) As _
    Byte()
    ' Remove any spaces.
    the_string = the_string.Replace(" ", "")

    ' Allocate room for the bytes.
    Dim bytes(the_string.Length / 2 - 1) As Byte

    ' Parse the letters in pairs.
    Dim byte_num As Integer = 0
    For i As Integer = 0 To the_string.Length - 1 Step 2
        bytes(byte_num) = _
            Byte.Parse(the_string.Substring(i, 2), _
                System.Globalization.NumberStyles.HexNumber)
        byte_num += 1
    Next i
    Return bytes
End Function
 
This method removes any spaces from the string. It allocates room for the bytes and loops through the string, parsing pairs of characters into the array.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated