首頁  >  文章  >  後端開發  >  在 C# 中如何將整數轉換為十六進位,反之亦然?

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

王林
王林轉載
2023-09-11 09:37:02916瀏覽

在 C# 中如何将整数转换为十六进制,反之亦然?

將整數轉換為十六進位

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

Integer Value: 500
Hexadecimal Value: 1F4

Converting Hexadecimal to Integer

A hexadecimal value can be converted to an integer using int.Parse or convert.ToInt32

int.Parse − Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the operation succeeded.

Hexadecimal Value: 1F4
Integer Value: 500

#Convert.ToInt32## - 將指定的值轉換為32位元有符號整數。

Hexadecimal Value: 1F4
Integer Value: 500

Converting Integer to Hexadecimal

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

Example

 Live Demo

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();
      }
   }
}

Output

The output of the above code is

Integer Value: 500
Hexadecimal Value: 1F4

Converting Hexadecimal to Integer

Example using int.Parse

Example

 Live Demo

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();
      }
   }
}

Output

#The output of the above code is

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();
      }
   }
}

Output

#The output of the above code is

Hexadecimal Value: 1F4
Integer Value: 500

以上是在 C# 中如何將整數轉換為十六進位,反之亦然?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除
上一篇:C# 字串方法下一篇:C# 字串方法