Tuesday, August 9, 2022

[FIXED] How to manually convert Hexadecimal to Decimal in C#?

Issue

So we were asked to convert a Hexadecimal Value (stored in a String) to its Decimal Value. Each character in the String should be manually converted to decimal within a loop, and then post the total Decimal Value of the Hexadecimal Value. I got here the codes that I have written but I couldn't identify where I could have gone wrong for an "F4" Hexa (as an example) to have a Decimal Equivalent of "292" instead of "244". I have debugged everything, the code seems fine. Any ideas?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdvProgCS
{
    class Program
    {
        static int dec=0;
        static string hex;
        static void Main(string[] args)
        {
            do{
                Console.Write("[Press 0 to Stop] Hexadecimal Value: ");

                hex = Console.ReadLine();
                if (hex == "0") break;
                int length = hex.Length;
                for (int i = 0; i < length+1; i++)
                {

                    if (hex[i] == 'A' || hex[i] == 'B' || hex[i] == 'C' || hex[i] == 'D' || hex[i] == 'E' || hex[i] == 'F')
                    {
                        if (hex[i] == 'A')
                            dec+= 10 * Convert.ToInt32(Math.Pow(16, length - 1));
                        if (hex[i] == 'B')
                            dec += 11 * Convert.ToInt32(Math.Pow(16, length - 1));
                        if (hex[i] == 'C')
                            dec += 12 * Convert.ToInt32(Math.Pow(16, length - 1));
                        if (hex[i] == 'D')
                            dec += 13 * Convert.ToInt32(Math.Pow(16, length - 1));
                        if (hex[i] == 'E')
                            dec += 14 * Convert.ToInt32(Math.Pow(16, length - 1));
                        if (hex[i] == 'F')
                            dec += 15 * (Convert.ToInt32(Math.Pow(16, length - 1)));
                    }
                    else
                        dec += hex[i];
                    length--;
                }
                Console.WriteLine("DECIMAL EQUIVALENT: " + dec + "\n");
            }
            while(hex != "0");

        }
    }
}

Solution

You forgot about the Math.Pow in the dec += hex[i] line where you also have to convert hex[i] from char into a number.

dec += (int)char.GetNumericValue(hex[i]) * (int)Math.Pow(16, length - 1);

Moreover, as observed by Partha:

Also add dec = 0; after your print statement. I think the dec values are getting adding to itself for each iteration.



Answered By - Dzienny
Answer Checked By - Marilyn (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.