简体   繁体   English

如何在C#中手动将十六进制转换为十进制?

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

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. String 中的每个字符都应该在一个循环中手动转换为十进制,然后将十六进制值的总十进制值贴出来。 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".我在这里找到了我编写的代码,但我无法确定“F4”Hexa(例如)的十进制等效值“292”而不是“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");

        }
    }
}

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 += hex[i]行中的Math.Pow ,您还必须将hex[i]从 char 转换为数字。

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

Moreover, as observed by Partha:此外,正如 Partha 所观察到的:

Also add dec = 0;还要加上 dec = 0; after your print statement.在您的打印声明之后。 I think the dec values are getting adding to itself for each iteration.我认为每次迭代的 dec 值都会增加。

Personally, my brain likes it better like this:就个人而言,我的大脑更喜欢这样:

    static void Main(string[] args)
    {
        int dec;
        string hex;
        int decValue;
        string hexReversed;
        string hexValues = "0123456789ABCDEF";

        do
        {
            Console.Write("[Press 0 to Stop] Hexadecimal Value: ");
            hex = Console.ReadLine().ToUpper().Trim();

            if (hex != "0")
            {
                dec = 0;
                hexReversed = new String(hex.Reverse().ToArray());
                for (int i = 0; i < hexReversed.Length; i++)
                {
                    decValue = hexValues.IndexOf(hexReversed.Substring(i, 1));
                    if (decValue != -1)
                    {
                        dec = dec + (decValue * (int)Math.Pow(16, i));
                    }
                    else
                    {
                        Console.WriteLine("Invalid Hexadecimal Value!");
                        break;
                    }
                }
                if (dec != 0)
                {
                    Console.WriteLine(String.Format("{0} hex = {1} dec", hex, dec.ToString()));
                }
            }
        } while (hex != "0");
    }

Here is my hex to decimal function, much smaller but it doesnt check if the input is a hex value or not.这是我的十六进制到十进制函数,小得多但它不检查输入是否为十六进制值。

private int hex2Decimal(string hex)
{
    string hexV = "0123456789ABCDEF"; // For the hex values (ex: F=15)
    hex = hex.ToUpper().Replace("0X", ""); // Get good string format
    int res;
    char[] cArr = hex.ToCharArray();
    Array.Reverse(cArr); // Reverse hex string
    List<int> iArr = new List<int>();
    for (int i = hex.Length - 1; i > -1; i--) // Get the bits
        iArr.Add(hexV.IndexOf(cArr[i]) * (int)Math.Pow(16, i)); // Calculate each bits and add to an array
    res = iArr.ToArray().Sum(); // Calculate all the numbers and add to the final result
    return res;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM