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

And*_*age 142 c# hex decimal type-conversion

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

And*_*age 269

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

string hexValue = decValue.ToString("X");
Run Code Online (Sandbox Code Playgroud)

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

int decValue = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
Run Code Online (Sandbox Code Playgroud)

要么

int decValue = Convert.ToInt32(hexValue, 16);
Run Code Online (Sandbox Code Playgroud)

  • 变量decValue的类型为Int32.Int32有一个ToString()重载,它可以接受许多格式字符串中的一个,这些格式字符串规定了如何将值表示为字符串."X"格式字符串表示十六进制,因此255.ToString("X")将返回十六进制字符串"FF".有关更多信息,请参阅http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx (20认同)
  • @VadymStetsiak Convert.ToInt32只调用Int32.Parse(int.Parse)(面掌) (9认同)
  • 我想了解这一行 decValue.ToString("X") 如何将其转换为十六进制。 (2认同)
  • Convert.ToInt32比int.Parse(...)具有更好的性能 (2认同)
  • 好答案.我实际上使用int.TryParse而不是int.Parse,以避免使用恼人的try catch块. (2认同)

Jon*_*upp 53

十六进制 - >十进制:

Convert.ToInt64(hexValue, 16);
Run Code Online (Sandbox Code Playgroud)

十进制 - >十六进制

string.format("{0:x}", decValue);
Run Code Online (Sandbox Code Playgroud)

  • +1关于`Convert.ToInt64(hexValue,16)的好处:`如果`0x`前缀存在与否,它将进行转换,而其他一些解决方案则不然. (5认同)

Jes*_*sen 26

看起来你可以说

Convert.ToInt64(value, 16)
Run Code Online (Sandbox Code Playgroud)

从十六进制中获取小数.

另一种方式是:

otherVar.ToString("X");
Run Code Online (Sandbox Code Playgroud)


Vad*_*iak 12

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

以下是说明该想法的代码.我的性能测试表明,它比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;
      }
  }
Run Code Online (Sandbox Code Playgroud)


Rob*_*Rob 5

从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);
Run Code Online (Sandbox Code Playgroud)