如何在C#中將整數轉換為十六進位制,反之亦然?


將整數轉換為十六進位制

可以使用string.ToString()擴充套件方法將整數轉換為十六進位制。

Integer Value: 500
Hexadecimal Value: 1F4

將十六進位制轉換為整數

可以使用int.Parse或Convert.ToInt32將十六進位制值轉換為整數

int.Parse − 將數字的字串表示形式轉換為其32位有符號整數等效值。返回值指示操作是否成功。

Hexadecimal Value: 1F4
Integer Value: 500

Convert.ToInt32 − 將指定值轉換為32位有符號整數。

Hexadecimal Value: 1F4
Integer Value: 500

將整數轉換為十六進位制

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

示例

 線上演示

using System;
namespace DemoApplication{
   public class Program{
      public static void Main(){
         int integerValue = 500;
         Console.WriteLine($"Integer Value: {integerValue}");
         string hexValue = integerValue.ToString("X");
         Console.WriteLine($"Hexadecimal Value: {hexValue}");
         Console.ReadLine();
      }
   }
}

輸出

以上程式碼的輸出為

Integer Value: 500
Hexadecimal Value: 1F4

將十六進位制轉換為整數

使用int.Parse的示例

示例

 線上演示

using System;
namespace DemoApplication{
   public class Program{
      public static void Main(){
         string hexValue = "1F4";
         Console.WriteLine($"Hexadecimal Value: {hexValue}");
         int integerValue = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
         Console.WriteLine($"Integer Value: {integerValue}");
         Console.ReadLine();
      }
   }
}

輸出

以上程式碼的輸出為

Hexadecimal Value: 1F4
Integer Value: 500

使用Convert.ToInt32的示例

示例

 線上演示

using System;
namespace DemoApplication{
   public class Program{
      public static void Main(){
         string hexValue = "1F4";
         Console.WriteLine($"Hexadecimal Value: {hexValue}");
         int integerValue = Convert.ToInt32(hexValue, 16);
         Console.WriteLine($"Integer Value: {integerValue}");
         Console.ReadLine();
      }
   }
}

輸出

以上程式碼的輸出為

Hexadecimal Value: 1F4
Integer Value: 500

更新於: 2020年8月19日

11K+ 次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.