Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,884 questions

51,810 answers

573 users

How to convert a hex string to a byte array in VB.NET

2 Answers

0 votes
Imports System
Imports System.Text
Imports System.Linq

Public Class Program
    Public Shared Sub PrintByteArray(ByVal bytes As Byte())
        Dim sb = New StringBuilder("byte[] = ")

        For Each b In bytes
            sb.Append(b & ", ")
        Next

        Console.WriteLine(sb.ToString())
    End Sub

    Public Shared Function HexStringToByteArray(ByVal hex As String) As Byte()
        hex = If(hex.Length Mod 2 = 1, "0" & hex, hex)
		
        Return Enumerable.Range(0, hex.Length).Where(Function(x) x Mod 2 = 0).Select(Function(x) Convert.ToByte(hex.Substring(x, 2), 16)).ToArray()
    End Function

    Public Shared Sub Main(ByVal args As String())
        Dim barr As Byte() = HexStringToByteArray("1B6E2AC")
				
        PrintByteArray(barr)
    End Sub
End Class

 
   
   
' run:
'
' byte[] = 1, 182, 226, 172,
'

 



answered Jun 20, 2024 by avibootz
0 votes
Imports System

Public Class Program
    Public Shared Sub PrintByteArray(ByVal barray As Byte())
        Console.Write("byte[] = ")

        For Each b As Byte In barray
            Console.Write(b.ToString("X2") & " ")
        Next

        Console.WriteLine()
    End Sub

    Public Shared Function HexStringToByteArray(ByVal hex As String) As Byte()
        hex = If(hex.Length Mod 2 = 1, "0" & hex, hex)
        Dim length As Integer = hex.Length
        Dim barr As Byte() = New Byte(length / 2 - 1) {}

        For i As Integer = 0 To length - 1 Step 2
            barr(i / 2) = Convert.ToByte(hex.Substring(i, 2), 16)
        Next

        Return barr
    End Function

    Public Shared Sub Main(ByVal args As String())
        Dim barr As Byte() = HexStringToByteArray("1B6E2AC")
	
        PrintByteArray(barr)
    End Sub
End Class
 
   
   
' run:
'
' byte[] = 01 B6 E2 AC
'

 



answered Jun 20, 2024 by avibootz

Related questions

2 answers 163 views
1 answer 168 views
168 views asked Jan 21, 2021 by avibootz
1 answer 420 views
1 answer 191 views
1 answer 180 views
180 views asked Jan 21, 2021 by avibootz
1 answer 246 views
1 answer 148 views
...