Pretty_Girl5
Pretty_Girl5

Reputation: 49

Hex to bytearray

 Dim data As String = "c80378b8"

 Dim bytes As Byte() = System.Text.RegularExpressions.Regex.Matches(Me.data.Substring, ".{2}").Select(Function(x) x.Value).ToArray()

Error 1

Overload resolution failed because no accessible 'Substring' accepts this number of arguments

I want to read the hex string in the data variable (2 characters at a time) and then that value (decimal) to be stored as binary format (bytes) in the bytes. But it produces above error, what is wrong with this and what is the correct method? is there any one liner alternative to this?

Upvotes: 1

Views: 2661

Answers (1)

Chris Dunaway
Chris Dunaway

Reputation: 11216

Try something like this:

Imports System.Globalization

Sub Main()
    Dim data As String = "c80378b8"
    Dim bytes As Byte() = BitConverter.GetBytes(Long.Parse(data, NumberStyles.AllowHexSpecifier))
End Sub

This code first parses the hex string to a Long and then gets the bytes for it. The parse will fail if the string is not a hex string. You may wish to put this code in a method so you can account for that possiblility.

EDIT:

If you need to convert strings longer than a Long variable will hold, you can use the BigInteger class. Add a reference to System.Numerics

Imports System.Numerics
Imports System.Globalization

Sub Main()
    Dim data As String = "4845484848484848484848484848484848484848484848484848484848484848"
    Dim bigI As BigInteger = BigInteger.Parse(data, NumberStyles.AllowHexSpecifier)
    Dim bytes As Byte() = bigI.ToByteArray()
End Sub

Upvotes: 1

Related Questions