Hex To Binary - CSharp System.IO

CSharp examples for System.IO:Hex

Description

Hex To Binary

Demo Code


using System.Text;
using System.Security.Principal;
using System.IO;//from  w  w w . j av a 2  s.c o  m
using System;

public class Main{
        private const string HexDigits = "0123456789ABCDEF";
        private static readonly byte[] HexValues = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
                                                                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                                                                0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F };
        public static byte[] HexToBinary(this string hex)
        {
            if (string.IsNullOrEmpty(hex))
            {
                return null;
            }

            // Finally, do the conversion:
            byte[] bytes = new byte[hex.Length / 2];
            for (int x = 0, i = 0; i < hex.Length; i += 2, x += 1)
            {
                bytes[x] = (byte)(HexValues[Char.ToUpper(hex[i + 0]) - '0'] << 4 |
                                  HexValues[Char.ToUpper(hex[i + 1]) - '0']);
            }

            return bytes;
        }
}

Related Tutorials