卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章1829本站已运行4109

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

在 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
卓越飞翔博客
上一篇: Golang如何实现高效的AI算法?
下一篇: PHP物联网硬件操作示例:通过代码实现设备连接
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏