ホームページ  >  記事  >  バックエンド開発  >  C#で整数を16進数に、またはその逆に変換するにはどうすればよいですか?

C#で整数を16進数に、またはその逆に変換するにはどうすればよいですか?

王林
王林転載
2023-09-11 09:37:02916ブラウズ

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

整数を 16 進数に変換する

string.ToString() 拡張メソッドを使用して、整数を 16 進数に変換できます。

Integer Value: 500
Hexadecimal Value: 1F4

16 進数から整数への変換 -

16 進数値は、int.Parse または Convert.ToInt32

を使用して整数に変換できます。 int.Parse - 数値の文字列表現を、同等の 32 ビット符号付き整数に変換します。戻り値は、操作が成功したかどうかを示します。

Hexadecimal Value: 1F4
Integer Value: 500

Convert.ToInt32 - Convert指定された値を 32 ビットの符号付き整数に変換します。

Hexadecimal Value: 1F4
Integer Value: 500

整数を 16 進数に変換

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

Example

ライブ デモ

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

16 進数を整数に変換 -

int.Parse を使用した例

Example

ライブ デモ

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 の使用例

-

Example

オンライン デモンストレーション

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

上記のコードの出力は
Hexadecimal Value: 1F4
Integer Value: 500
###です

以上がC#で整数を16進数に、またはその逆に変換するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はtutorialspoint.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。