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.

40,026 questions

51,982 answers

573 users

How to convert a hex string to a byte array in C#

2 Answers

0 votes
using System;
using System.Text;
using System.Linq;

internal class Program
{
	static void PrintByteArray(byte[] bytes) {
        var sb = new StringBuilder("byte[] = ");
  
        foreach (var b in bytes) {
            sb.Append(b + ", ");
        }
  
        Console.WriteLine(sb.ToString());
    }
    
    public static byte[] HexStringToByteArray(string hex) {
        hex = hex.Length % 2 == 1 ? "0" + hex : hex; // Pad with leading zero if necessary
        
        return Enumerable.Range(0, hex.Length)
                     .Where(x => x % 2 == 0)
                     .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                     .ToArray();
    }

	public static void Main(string[] args)
	{
		byte[] barr = HexStringToByteArray("1B6E2AC"); 

		PrintByteArray(barr);
	}
}



/*
run:
  
byte[] = 1, 182, 226, 172, 
  
*/

 



answered Jun 20, 2024 by avibootz
edited Jun 20, 2024 by avibootz
0 votes
using System;

internal class Program
{
	static void PrintByteArray(byte[] barray) {
        Console.Write("byte[] = ");
  
        foreach (byte b in barray) {
            Console.Write(b.ToString("X2") + " ");
        }
        
        Console.WriteLine();
    }
    
    public static byte[] HexStringToByteArray(string hex) {
        hex = hex.Length % 2 == 1 ? "0" + hex : hex; // Pad with leading zero if necessary
        
        int length = hex.Length;
        byte[] barr = new byte[length / 2];

        for (int i = 0; i < length; i += 2) {
            barr[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
        }
        
        return barr;
    }

	public static void Main(string[] args)
	{
		byte[] barr = HexStringToByteArray("1B6E2AC"); 

		PrintByteArray(barr);
	}
}



/*
run:
  
byte[] = 01 B6 E2 AC 
  
*/

 



answered Jun 20, 2024 by avibootz

Related questions

...