[英]How to manually convert Hexadecimal to Decimal in C#?
因此,我們被要求將十六進制值(存儲在字符串中)轉換為其十進制值。 String 中的每個字符都應該在一個循環中手動轉換為十進制,然后將十六進制值的總十進制值貼出來。 我在這里找到了我編寫的代碼,但我無法確定“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");
}
}
}
您忘記了dec += hex[i]
行中的Math.Pow
,您還必須將hex[i]
從 char 轉換為數字。
dec += (int)char.GetNumericValue(hex[i]) * (int)Math.Pow(16, length - 1);
此外,正如 Partha 所觀察到的:
還要加上 dec = 0; 在您的打印聲明之后。 我認為每次迭代的 dec 值都會增加。
就個人而言,我的大腦更喜歡這樣:
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");
}
這是我的十六進制到十進制函數,小得多但它不檢查輸入是否為十六進制值。
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.