数値を16進数表記で表示する - Formatメソッドの利用 - C#

Formatメソッドを用いて数値を16進数表記で表示するコードを紹介します。

概要

Formatメソッドで16進数表示する場合は、標準の数値書式指定文字列の"X"を用います。
数値書式指定文字列の詳細はこちらの記事を参照してください。

書式

{(インデックス番号):x}
{(インデックス番号):X}

テストプログラム

UI

下図のUIを作成します。TextBoxを1つ、Buttonを1つ配置します。

コード

以下のコードを記述します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace NumericFormatDemo
{
  public partial class FormNAryNumber : Form
  {
    public FormNAryNumber()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      int value = 50219;
      textBox1.Text += string.Format("{0:X}", value);
    }
  }
}

解説

  string.Format("{0:X}", value);
Formatメソッドの書式指定文字列で"X"を指定すると16進数表記で整形されます。

実行結果

プロジェクトを実行します。下図のウィンドウが表示されます。


[Format "X"]のボタンをクリックします。コードに記載した"50219"を16進数表記した"C42B"がテキストボックスに表示されます。

著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-05-25
作成日: 2014-08-20
iPentec all rights reserverd.