Computer >> Máy Tính >  >> Lập trình >> C#

Làm thế nào để chuyển đổi một số nguyên sang hệ thập lục phân và ngược lại trong C #?

Chuyển đổi số nguyên sang hệ thập lục phân

Một số nguyên có thể được chuyển đổi thành hệ thập lục phân bằng cách sử dụng phương thức mở rộng string.ToString ().

Integer Value: 500
Hexadecimal Value: 1F4

Chuyển đổi hệ thập lục phân thành số nguyên -

Giá trị thập lục phân có thể được chuyển đổi thành số nguyên bằng cách sử dụng int.Parse hoặc convert.ToInt32

int.Parse - Chuyển đổi biểu diễn chuỗi của một số thành số nguyên có dấu 32-bit tương đương của nó. Giá trị trả về cho biết thao tác có thành công hay không.

Hexadecimal Value: 1F4
Integer Value: 500

Convert.ToInt32 −Chuyển đổi một giá trị được chỉ định thành số nguyên có dấu 32 bit.

Hexadecimal Value: 1F4
Integer Value: 500

Chuyển đổi số nguyên sang hệ thập lục phân -

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

Ví dụ

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

Đầu ra

Đầu ra của đoạn mã trên là

Integer Value: 500
Hexadecimal Value: 1F4

Chuyển đổi hệ thập lục phân thành số nguyên -

Ví dụ sử dụng int.Parse -

Ví dụ

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

Đầu ra

Đầu ra của đoạn mã trên là

Hexadecimal Value: 1F4
Integer Value: 500

Ví dụ sử dụng Convert.ToInt32 -

Ví dụ

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

Đầu ra

Đầu ra của đoạn mã trên là

Hexadecimal Value: 1F4
Integer Value: 500