【问题标题】:How to manually convert Hexadecimal to Decimal in C#?如何在 C# 中手动将十六进制转换为十进制?
【发布时间】:2015-09-21 14:33:21
【问题描述】:

所以我们被要求将十六进制值(存储在字符串中)转换为其十进制值。字符串中的每个字符都应在循环内手动转换为十进制,然后发布十六进制值的总十进制值。我得到了我编写的代码,但我无法确定我可能在哪里出错,因为“F4”Hexa(例如)具有“292”而不是“244”的十进制等效值。我已经调试了所有东西,代码看起来很好。有什么想法吗?

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");

        }
    }
}

【问题讨论】:

标签: c# command-line hex decimal


【解决方案1】:

这是我的十六进制转十进制函数,小得多,但它不检查输入是否为十六进制值。

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;
}

【讨论】:

    【解决方案2】:

    就个人而言,我的大脑更喜欢这样:

        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");
        }
    

    【讨论】:

      【解决方案3】:

      您忘记了dec += hex[i] 行中的Math.Pow,您还必须将hex[i] 从字符转换为数字。

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

      此外,正如 Partha 所观察到的:

      还要加上 dec = 0;在您的打印声明之后。我认为 dec 值 每次迭代都会增加自己。

      【讨论】:

      • 还添加 dec = 0;在您的打印声明之后。我认为每次迭代的 dec 值都会增加。
      • @Partha 很好,如果您不介意,我将其添加到答案中。
      • 谢谢!从 char 到 int 的转换和 math.pow 成功了! :) 哦,是的,也感谢 dec=0 ! :)
      • @Maranatha 既然回答了你的问题,你可以把它标记为答案;)
      猜你喜欢
      • 2017-07-31
      • 2013-07-20
      • 2012-06-17
      • 2023-03-31
      • 2021-06-26
      • 2011-07-11
      • 1970-01-01
      • 2015-12-03
      • 2015-09-13
      相关资源
      最近更新 更多