簡體   English   中英

十六進制到字符串的奇怪間距

[英]Weird spacing in Hex to String

我試圖做一個十六進制到字符串的轉換器,由於某種原因,轉換中字節之間的間隔乘以2。

我希望它在字符之間吐出一個空格,

private void button2_Click(object sender, EventArgs e)
{
    try
    {
        textBox1.Clear();
        textBox2.Text = textBox2.Text.Replace(" ", "");
        string StrValue = "";
        while (textBox2.Text.Length > 0)
        {
            StrValue += System.Convert.ToChar(System.Convert.ToUInt32(textBox2.Text.Substring(0, 2), 16)).ToString();
            textBox2.Text = textBox2.Text.Substring(2, textBox2.Text.Length - 2);             
            textBox1.Text = textBox1.Text + StrValue + " ";
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Conversion Error Occurred : " + ex.Message, "Conversion Error");
    }
}

所以轉換后的“ 41 41”看起來像“ AA”,但是會發生以下情況: image有人看到我在做什么嗎?

在這條線

textBox1.Text = textBox1.Text + StrValue + " ";

因此,您將計算結果附加到TextBox1

因此,在第一次迭代后,結果是A ,將其附加一個空格並添加到TextBox1 然后,取第二個41並將其轉換。 現在, StrValueAA ,並將其和空格附加到TextBox1 ,依此類推。

您需要將此行移出while循環:

textBox1.Clear();
textBox2.Text = textBox2.Text.Replace(" ", "");

string StrValue = "";

while (textBox2.Text.Length > 0)
{

    StrValue += System.Convert.ToChar(System.Convert.ToUInt32(textBox2.Text.Substring(0, 2), 16)).ToString();
    textBox2.Text = textBox2.Text.Substring(2, textBox2.Text.Length - 2);             
}

textBox1.Text = StrValue;

正如某些人在評論中提到的那樣,您需要以這種方式停止使用TextBox 這很令人困惑。 您可能需要執行以下操作:

private string HexToString(string hex)
{
    string result = "";

    while (hex.Length > 0) 
    {
        result += Convert.ToChar(Convert.ToUInt32(hex.Substring(0, 2), 16));
        hex = hex.Substring(2); // no need to specify the end
    }

    return result;
}

然后,在您的按鈕單擊事件或其他任何地方:

textBox1.Text = HexToString(textBox2.Text.Replace(" ", "")); 

就如此容易。 或者,您甚至可以移動替換方法中的空格。 現在,此代碼是可讀的並且在邏輯上是分開的。

該問題似乎是由於StrValue的累加值引起的。 您應該在while內定義該變量,並僅對其進行分配(不要附加新值)。

while (textBox2.Text.Length > 0)
{
    string StrValue = System.Convert.ToChar(System.Convert.ToUInt32(textBox2.Text.Substring(0, 2), 16)).ToString();
    textBox2.Text = textBox2.Text.Substring(2, textBox2.Text.Length - 2);             
    textBox1.Text = textBox1.Text + StrValue + " ";
}

暫無
暫無

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

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