CopyPastehas never been so tasty!

Convert hex to binary and byte array in C#

by anonymous

  • 0
  • 0
  • 0
72 views

Convert Class:

 

We use Convert class to convert one data type to the other data type. It has overloaded static methods. Static methods are that methods which only call by class name and we cannot call them by object name.

 

Convert hex to binary:

 

To convert hexadecimal into binary we use Convert class and its method “ToString” it takes two parameters. And to convert the given number into hexadecimal we use the function “ToInt32” of Convert class. It takes two parameters first is the value and second is the base and base of hexadecimal is 16. This method will take a hexadecimal number and convert it into binary number.

 

To demonstrate make a console application and write following code

 

 

Code:

 

 

classhexa2binary

    {

staticvoid Main(string[] args)

        {

try

            {

//hexvaluetake any hexadecimal number

stringhexvalue = "A";

stringbinaryval = "";

binaryval = Convert.ToString(Convert.ToInt32(hexvalue, 16), 2);

Console.WriteLine(binaryval);

Console.ReadLine();

            }

catch (Exceptionexce)

            {

Console.WriteLine(exce.ToString());

 

            }

        }

    }

 

 

Convert hex to byte array:

 

To convert the hexadecimal to byte array we use the UTF8 Encoding class. And to convert the hexadecimal into byte array we use method GetByte and save it into a byte array. Than we use for loop to get data from the byte array. By using the following code you can convert the hexadecimal to byte array.

 

To demonstrate make a console application, and write the following code in main.

 

 

Code:

 

staticvoid Main(string[] args)

        {

 

byte[] array = System.Text.Encoding.UTF8.GetBytes("Abc");

 

 

for (int x = 0; x <array.Length; x++)

            {

Console.WriteLine("\n" + array[x].ToString());

 

            }

Console.ReadLine();

 

        }

Add A Comment: