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

...