簡體   English   中英

在“離開”文本框后將十六進制字符串格式化為字節數組

[英]Format a HEX string as byte array after "leave" the textbox

我已經使用 Windows 窗體制作了一個小應用程序,我可以在其中輸入十六進制數並將其轉換為十進制數,但是當我在文本框外單擊時,我不知道如何自動格式化文本框中的文本,我已經在互聯網上搜索並發現“OnLeave”操作是我所需要的。 當我說格式化文本時,我指的是:

Value 1: 0x00aa00bb -> 0x 00 aa 00 bb
Value 2: 45aa00CC -> 45 aa 00 cc

就像我有一個字節數組一樣格式化它們,因為我想用它來將十六進制轉換為浮點數,這種方式更具可讀性。

只需使用一個簡單的“for 循環”來解析您輸入的值,在每次迭代中選擇 2 個字符並在它們后面附加一個空格:

private void txtHexadecimal_Leave(object sender, EventArgs e)
        {
            String value = txtHexadecimal.Text;
            value = value.Replace(" ", String.Empty);
            if (value.Length % 2 == 0)
            {
                String output = "";
                int spliceValue_B = 0;
                for (int i = 0; i < value.Length / 2; i++)
                {
                    String sp = value.Substring(spliceValue_B, 2);
                    if (i != (value.Length / 2) - 1)
                        sp += " ";
                    output += sp;
                    spliceValue_B += 2;
                }

                txtHexadecimal.Text = output;
            }
        }

這是另一種方法,只是因為這是本周迄今為止我最喜歡的星期一:

private void txtHexadecimal_Leave(object sender, EventArgs e)
{
    bool addSpaceBefore = true;
    StringBuilder sb = new StringBuilder();
    foreach(char c in txtHexadecimal.Text.Where(x => !char.IsWhiteSpace(x))) {
        if (addSpaceBefore && sb.Length>0)
        {
            sb.Append(' ');
        }
        sb.Append(c);
        addSpaceBefore = !addSpaceBefore;
    }
    txtHexadecimal.Text = sb.ToString();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM