Home » C#.Net

Print integer values from an array of strings containing hexadecimal values in C#

C# | printing integer values from an array of hexadecimal strings: Here, we are going to learn how to convert an array of strings that contains hexadecimal values in integers?
Submitted by IncludeHelp, on February 09, 2019

Converting array of hexadecimal strings to integers

Let suppose you have some of the strings (i.e. array of strings) containing hexadecimal values like "AA", "ABCD", "ff21", "3039", "FAFA" which are equivalent to integers 170, 43981, 65313, 12345, 64250.

As we have written in the previous post: convert hexadecimal string to integer, we use Convert.ToInt32() function to convert the values.

We will access each item using a foreach loop, and convert the item to an integer using base value 16.

Code:

using System;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] str = { "AA", "ABCD", "ff21", "3039", "FAFA"};
            int num = 0;
            try
            {
                //using foreach loop to access each items
                //and converting to integer numbers 
                foreach (string item in str)
                {
                    num = Convert.ToInt32(item, 16);
                    Console.WriteLine(num);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            //hit ENTER to exit
            Console.ReadLine();
        }
    }
}

Output

170
43981
65313
12345
64250



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.