如何在十六进制和十进制之间转换数字

173

在C#中,如何在十六进制数和十进制数之间进行转换?

20个回答

1

四种C#本地方法将十六进制转换为十进制并相互转换:

using System;

namespace Hexadecimal_and_Decimal
{
  internal class Program
  {
    private static void Main(string[] args)
    {
      string hex = "4DEAD";
      int dec;

      // hex to dec:
      dec = int.Parse(hex, System.Globalization.NumberStyles.HexNumber);
      // or:
      dec = Convert.ToInt32(hex, 16);

      // dec to hex:
      hex = dec.ToString("X"); // lowcase: x, uppercase: X
      // or:
      hex = string.Format("{0:X}", dec); // lowcase: x, uppercase: X

      Console.WriteLine("Hexadecimal number: " + hex);
      Console.WriteLine("Decimal number: " + dec);
    }
  }
}

1
这个对我有用:

public static decimal HexToDec(string hex)
{
  if (hex.Length % 2 == 1)
    hex = "0" + hex;
  byte[] raw = new byte[hex.Length / 2];
  decimal d = 0;
    for (int i = 0; i < raw.Length; i++)
    {
      raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
      d += Math.Pow(256, (raw.Length - 1 - i)) * raw[i];
    }
    return d.ToString();
  return d;
}

1
    static string chex(byte e)                  // Convert a byte to a string representing that byte in hexadecimal
    {
        string r = "";
        string chars = "0123456789ABCDEF";
        r += chars[e >> 4];
        return r += chars[e &= 0x0F];
    }           // Easy enough...

    static byte CRAZY_BYTE(string t, int i)     // Take a byte, if zero return zero, else throw exception (i=0 means false, i>0 means true)
    {
        if (i == 0) return 0;
        throw new Exception(t);
    }

    static byte hbyte(string e)                 // Take 2 characters: these are hex chars, convert it to a byte
    {                                           // WARNING: This code will make small children cry. Rated R.
        e = e.ToUpper(); // 
        string msg = "INVALID CHARS";           // The message that will be thrown if the hex str is invalid

        byte[] t = new byte[]                   // Gets the 2 characters and puts them in seperate entries in a byte array.
        {                                       // This will throw an exception if (e.Length != 2).
            (byte)e[CRAZY_BYTE("INVALID LENGTH", e.Length ^ 0x02)], 
            (byte)e[0x01] 
        };

        for (byte i = 0x00; i < 0x02; i++)      // Convert those [ascii] characters to [hexadecimal] characters. Error out if either character is invalid.
        {
            t[i] -= (byte)((t[i] >= 0x30) ? 0x30 : CRAZY_BYTE(msg, 0x01));                                  // Check for 0-9
            t[i] -= (byte)((!(t[i] < 0x0A)) ? (t[i] >= 0x11 ? 0x07 : CRAZY_BYTE(msg, 0x01)) : 0x00);        // Check for A-F
        }           

        return t[0x01] |= t[0x00] <<= 0x04;     // The moment of truth.
    }

1

这不是最简单的方法,但这段源代码可以让你正确处理任何类型的八进制数,例如 23.214、23 和 0.512 等等。希望这能帮到你。

    public string octal_to_decimal(string m_value)
    {
        double i, j, x = 0;
        Int64 main_value;
        int k = 0;
        bool pw = true, ch;
        int position_pt = m_value.IndexOf(".");
        if (position_pt == -1)
        {
            main_value = Convert.ToInt64(m_value);
            ch = false;
        }
        else
        {
            main_value = Convert.ToInt64(m_value.Remove(position_pt, m_value.Length - position_pt));
            ch = true;
        }

        while (k <= 1)
        {
            do
            {
                i = main_value % 10;                                        // Return Remainder
                i = i * Convert.ToDouble(Math.Pow(8, x));                   // calculate power
                if (pw)
                    x++;
                else
                    x--;
                o_to_d = o_to_d + i;                                        // Saving Required calculated value in main variable
                main_value = main_value / 10;                               // Dividing the main value 
            }
            while (main_value >= 1);
            if (ch)
            {
                k++;
                main_value = Convert.ToInt64(Reversestring(m_value.Remove(0, position_pt + 1)));
            }
            else
                k = 2;
            pw = false;
            x = -1;
        }
        return (Convert.ToString(o_to_d));
    }    

2
欢迎来到stackoverflow。您能否简单解释一下您的代码(也许只需要一个简短的句子)?谢谢! - Daniele B

0

我的版本更易于理解,因为我的C#知识不是很高。 我使用的算法是:http://easyguyevo.hubpages.com/hub/Convert-Hex-to-Decimal(示例2)

using System;
using System.Collections.Generic;

static class Tool
{
    public static string DecToHex(int x)
    {
        string result = "";

        while (x != 0)
        {
            if ((x % 16) < 10)
                result = x % 16 + result;
            else
            {
                string temp = "";

                switch (x % 16)
                {
                    case 10: temp = "A"; break;
                    case 11: temp = "B"; break;
                    case 12: temp = "C"; break;
                    case 13: temp = "D"; break;
                    case 14: temp = "E"; break;
                    case 15: temp = "F"; break;
                }

                result = temp + result;
            }

            x /= 16;
        }

        return result;
    }

    public static int HexToDec(string x)
    {
        int result = 0;
        int count = x.Length - 1;
        for (int i = 0; i < x.Length; i++)
        {
            int temp = 0;
            switch (x[i])
            {
                case 'A': temp = 10; break;
                case 'B': temp = 11; break;
                case 'C': temp = 12; break;
                case 'D': temp = 13; break;
                case 'E': temp = 14; break;
                case 'F': temp = 15; break;
                default: temp = -48 + (int)x[i]; break; // -48 because of ASCII
            }

            result += temp * (int)(Math.Pow(16, count));
            count--;
        }

        return result;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Console.Write("Enter Decimal value: ");
        int decNum = int.Parse(Console.ReadLine());

        Console.WriteLine("Dec {0} is hex {1}", decNum, Tool.DecToHex(decNum));

        Console.Write("\nEnter Hexadecimal value: ");
        string hexNum = Console.ReadLine().ToUpper();

        Console.WriteLine("Hex {0} is dec {1}", hexNum, Tool.HexToDec(hexNum));

        Console.ReadKey();
    }
}

0

将二进制转换为十六进制

Convert.ToString(Convert.ToUInt32(binary1, 2), 16).ToUpper()

0

您可以使用此代码,并可能设置十六进制长度和部分:

const int decimal_places = 4;
const int int_places = 4;
static readonly string decimal_places_format = $"X{decimal_places}";
static readonly string int_places_format = $"X{int_places}";

public static string DecimaltoHex(decimal number)
{
    var n = (int)Math.Truncate(number);
    var f = (int)Math.Truncate((number - n) * ((decimal)Math.Pow(10, decimal_places)));
    return $"{string.Format($"{{0:{int_places_format}}}", n)}{string.Format($"{{0:{decimal_places_format}}}", f)}";
}

public static decimal HextoDecimal(string number)
{
    var n = number.Substring(0, number.Length - decimal_places);
    var f = number.Substring(number.Length - decimal_places);
    return decimal.Parse($"{int.Parse(n, System.Globalization.NumberStyles.HexNumber)}.{int.Parse(f, System.Globalization.NumberStyles.HexNumber)}");
}

-1
一个将字节数组转换为十六进制表示的扩展方法。它会在每个字节前面填充零。
    /// <summary>
    /// Turns the byte array into its Hex representation.
    /// </summary>
    public static string ToHex(this byte[] y)
    {
        StringBuilder sb = new StringBuilder();
        foreach (byte b in y)
        {
            sb.Append(b.ToString("X").PadLeft(2, "0"[0]));
        }
        return sb.ToString();
    }

-1

这是我的函数:

using System;
using System.Collections.Generic;
class HexadecimalToDecimal
{
    static Dictionary<char, int> hexdecval = new Dictionary<char, int>{
        {'0', 0},
        {'1', 1},
        {'2', 2},
        {'3', 3},
        {'4', 4},
        {'5', 5},
        {'6', 6},
        {'7', 7},
        {'8', 8},
        {'9', 9},
        {'a', 10},
        {'b', 11},
        {'c', 12},
        {'d', 13},
        {'e', 14},
        {'f', 15},
    };

    static decimal HexToDec(string hex)
    {
        decimal result = 0;
        hex = hex.ToLower();

        for (int i = 0; i < hex.Length; i++)
        {
            char valAt = hex[hex.Length - 1 - i];
            result += hexdecval[valAt] * (int)Math.Pow(16, i);
        }

        return result;
    }

    static void Main()
    {

        Console.WriteLine("Enter Hexadecimal value");
        string hex = Console.ReadLine().Trim();

        //string hex = "29A";
        Console.WriteLine("Hex {0} is dec {1}", hex, HexToDec(hex));

        Console.ReadKey();
    }
}

这可能是一个很好的候选项,可以用于创建一个 Convert 扩展方法,这样就可以写成:int hexa = Convert.ToHexadecimal(11); =) - Will Marcouiller

-1

我的解决方案有点像回到基础,但它可以在不使用任何内置函数转换数字系统的情况下工作。

    public static string DecToHex(long a)
    {
        int n = 1;
        long b = a;
        while (b > 15)
        {
            b /= 16;
            n++;
        }
        string[] t = new string[n];
        int i = 0, j = n - 1;
        do
        {
                 if (a % 16 == 10) t[i] = "A";
            else if (a % 16 == 11) t[i] = "B";
            else if (a % 16 == 12) t[i] = "C";
            else if (a % 16 == 13) t[i] = "D";
            else if (a % 16 == 14) t[i] = "E";
            else if (a % 16 == 15) t[i] = "F";
            else t[i] = (a % 16).ToString();
            a /= 16;
            i++;
        }
        while ((a * 16) > 15);
        string[] r = new string[n];
        for (i = 0; i < n; i++)
        {
            r[i] = t[j];
            j--;
        }
        string res = string.Concat(r);
        return res;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接