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

c# hex type-conversion decimal

286388 观看

15回复

19382 作者的声誉

如何在C#中转换十六进制数和十进制数?

作者: Andy McCluggage 的来源 发布者: 2008 年 9 月 16 日

回应 (15)


1

23620 作者的声誉

String stringrep = myintvar.ToString("X");

int num = int.Parse("FF", System.Globalization.NumberStyles.HexNumber);
作者: Sklivvz 发布者: 16.09.2008 04:21

24

2361 作者的声誉

看起来你可以说

Convert.ToInt64(value, 16)

从十六进制中获取小数。

另一种方式是:

otherVar.ToString("X");
作者: Jesper Blad Jensen 发布者: 16.09.2008 04:22

3

463 作者的声誉

来自Geekpedia

// Store integer 182
int decValue = 182;

// Convert integer 182 as a hex in a string variable
string hexValue = decValue.ToString("X");

// Convert the hex string back to the number
int decAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
作者: Rob 发布者: 16.09.2008 04:22

49

13434 作者的声誉

十六进制 - >十进制:

Convert.ToInt64(hexValue, 16);

十进制 - >十六进制

string.format("{0:x}", decValue);
作者: Jonathan Rupp 发布者: 16.09.2008 04:23

249

19382 作者的声誉

决定

要从十进制转换为十六进制,请...

string hexValue = decValue.ToString("X");

要从十六进制转换为十进制,请执行...

int decValue = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);

要么

int decValue = Convert.ToInt32(hexValue, 16);
作者: Andy McCluggage 发布者: 16.09.2008 04:26

2

29 作者的声誉

    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.
    }
作者: Ecstatic Coder 发布者: 20.03.2010 06:39

2

21 作者的声誉

这不是最简单的方法,但是这个源代码可以让你找到任何类型的八进制数,即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));
    }    
作者: Omair 发布者: 17.12.2010 09:40

0

1204 作者的声誉

如果它是超出普通整数容量的非常大的十六进制字符串:

对于.NET 3.5,我们可以使用BouncyCastle的BigInteger类:

String hex = "68c7b05d0000000002f8";
// results in "494809724602834812404472"
String decimal = new Org.BouncyCastle.Math.BigInteger(hex, 16).ToString();

.NET 4.0具有BigInteger类。

作者: msanjay 发布者: 01.06.2011 05:47

-1

19589 作者的声誉

一种将字节数组转换为十六进制表示的扩展方法。这将每个字节填充为前导零。

    /// <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();
    }
作者: Luke Puplett 发布者: 12.07.2011 03:27

12

1669 作者的声誉

如果要在从十六进制转换为十进制数时获得最大性能,则可以使用预先填充的十六进制到十进制值表的方法。

以下是说明该想法的代码。我的性能测试表明,它比Convert.ToInt32(...)快20%-40%:

class TableConvert
  {
      static sbyte[] unhex_table =
      { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
       ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
       ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
       , 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1
       ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
       ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
       ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
       ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
      };

      public static int Convert(string hexNumber)
      {
          int decValue = unhex_table[(byte)hexNumber[0]];
          for (int i = 1; i < hexNumber.Length; i++)
          {
              decValue *= 16;
              decValue += unhex_table[(byte)hexNumber[i]];
          }
          return decValue;
      }
  }
作者: Vadym Stetsiak 发布者: 03.02.2012 09:57

0

833 作者的声誉

这是我的功能:

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();
    }
}
作者: Христо Панайотов 发布者: 12.01.2014 08:00

0

3 作者的声誉

我认为我的版本更容易理解,因为我的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();
    }
}
作者: Mihók Balázs 发布者: 09.02.2015 10:58

0

11 作者的声誉

将二进制转换为Hex

Convert.ToString(Convert.ToUInt32(binary1, 2), 16).ToUpper()
作者: Jewel 发布者: 29.04.2015 09:35

2

49 作者的声誉

十六进制到十进制转换

Convert.ToInt32(number, 16);

十进制到十六进制转换

int.Parse(number, System.Globalization.NumberStyles.HexNumber)

有关详细信息,请查看此文章

作者: user7925882 发布者: 22.05.2017 07:20

1

1903 作者的声誉

尝试在C#中使用BigNumber - 表示任意大的有符号整数。

程序

using System.Numerics;
...
var bigNumber = BigInteger.Parse("837593454735734579347547357233757342857087879423437472347757234945743");
Console.WriteLine(bigNumber.ToString("X"));

产量

4F30DC39A5B10A824134D5B18EEA3707AC854EE565414ED2E498DCFDE1A15DA5FEB6074AE248458435BD417F06F674EB29A2CFECF

可能的例外情况,

ArgumentNullException - value为null。

FormatException - 值的格式不正确。

结论

您可以转换字符串并在BigNumber中存储值,而不受数字大小的限制,除非字符串为空且非analphabets

作者: Aravin 发布者: 30.03.2018 06:54
32x32