Last active
July 28, 2024 10:58
-
-
Save unot/e13678cc8b873d6112755a396d5af937 to your computer and use it in GitHub Desktop.
入力文字列を、指定された文字数にスペース埋めした後に16進数ASCIIコードに変換、2文字ずつスペースで連結
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Windows.Forms; | |
namespace StringToHexConverter | |
{ | |
public partial class Form1 : Form | |
{ | |
public Form1() | |
{ | |
InitializeComponent(); | |
} | |
private void btnConvertText_Click(object sender, EventArgs e) | |
{ | |
// テキストボックスから文字列を取得 | |
string srcText = txtInput.Text; | |
// コンボボックスから文字列を取得して数値に変換 | |
_ = int.TryParse(cmbInputTextCount.Text, result: out int textcount); | |
// 文字列を指定文字数に揃える | |
string paddedString = textcount >= srcText.Length ? srcText.PadRight(textcount) : srcText.Substring(0, textcount); | |
//TODO: 文字列から2文字ずつ取り出して16進数ASCIIコードに変換し、スペースで連結 | |
string hexResult = ConvertToHexAscii(paddedString); | |
// テキストボックスに表示 | |
txtOutput.Text = hexResult; | |
} | |
/// <summary> | |
/// 文字列を16進数ASCIIコードに変換し、2文字ごとにスペースを挿入する | |
/// </summary> | |
/// <param name="input">入力文字列</param> | |
/// <returns>出力文字列</returns> | |
private static string ConvertToHexAscii(string input) | |
{ | |
string hexResult = ""; | |
string delim = " "; | |
foreach (char c in input) | |
{ | |
int asciiCode = (int)c; | |
string hexCode = asciiCode.ToString("X2"); // 2桁の16進数に変換 | |
delim = delim == " " ? "" : " "; | |
hexResult += hexCode + delim; // スペースで連結 | |
} | |
return hexResult.TrimEnd(' '); // 末尾のスペースを削除 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment