CopyPastehas never been so tasty!

Convert Hex into byte, integer and Unicode in C#

by anonymous

  • 0
  • 0
  • 0
142 views

Convert Hex into byte, integer and Unicode in C#

Hex NumbersHexadecimal numbers uses sixteen distinct symbols, the symbols 0-9 represent values zero to nine and A, B, C, D, E, F (or alternatively a–f) to represent values from ten to fifteen.Hex to ByteIn C# byte data type represents an 8-bit unsigned integer .Following code will illustrate the conversion of hex into Byte.using System.Globalization;

static void Main(string[] args)

        {

             string string2 = "c5";

            byte byte2 = Byte.Parse(string2, NumberStyles.HexNumber);

            Console.WriteLine("" + byte2);

            Console.ReadLine();

}

 Output is 197 as byte code for c5 is 197

 Hex to IntegerFollowing code will illustrate conversion of hex into integer.

         static void Main(string[] args)

        {

            Program.HexToInt('h');

            Console.WriteLine(Program.HexToInt('h'));

            Console.ReadLine();

        }

public static int HexToInt(char h)

        {

            h = 'f';

            if ((h >= '0') && (h <= '9'))

            {

                return (h - '0');

            }

            if ((h >= 'a') && (h <= 'f'))

            {

                return ((h - 'a') + 10);

            }

            if ((h >= 'A') && (h <= 'F'))

            {

                return ((h - 'A') + 10);

            }

            else

            return -1;

        }//Output is 15 which is an integer.

 Hex to UnicodeReturns the integer value, as defined by the Unicode standard. Following code will illustrate conversion of hex into Unicode

 static void Main(string[] args)

        {

             Program.Hextounicode("50");

            Console.WriteLine(Hextounicode("50"));

            Console.ReadLine();

        }

        public static string Hextounicode(string hex)

        {

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i <= hex.Length - 2; i += 2)

            {

                sb.Append(Convert.ToString(Convert.ToChar(Int32.Parse(hex.Substring(i, 2), NumberStyles.HexNumber))));

            }

            return sb.ToString();

        }//Output is P as Unicode for P is 50

 

Add A Comment: