Hex String To Bytes - CSharp System

CSharp examples for System:Byte

Description

Hex String To Bytes

Demo Code


using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;//from   w ww  .  ja  va  2s . c  o m

public class Main{
        public static byte[] HexStringToBytes(string hex)
        {
            if (hex.Length == 0)
            {
                return new byte[] { 0 };
            }

            if (hex.Length % 2 == 1)
            {
                hex = "0" + hex;
            }

            byte[] result = new byte[hex.Length / 2];

            for (int i = 0; i < hex.Length / 2; i++)
            {
                result[i] = byte.Parse(hex.Substring(2 * i, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
            }

            return result;
        }
}

Related Tutorials