-1

OK so I'm making a ASCII to HEX converter and it works fine, but when i insert line breaks it replaces them with this character -> Ú

ie
turns this

1
2
3

to this

1Ú2Ú3

Code under command buttons

    private void asciiToHex_Click(object sender, EventArgs e)
    {
        HexConverter HexConvert =new HexConverter();
        string sData=textBox1.Text;
        textBox2.Text = HexConvert.StringToHexadecimal(sData);
    }

    private void hexToAscii_Click(object sender, EventArgs e)
    {
        HexConverter HexConvert = new HexConverter();
        string sData = textBox1.Text;
        textBox2.Text = HexConvert.HexadecimalToString(sData);
    }

Code under HexConverter.cs

public class HexConverter
{
    public string HexadecimalToString(string Data)
    {
        string Data1 = "";
        string sData = "";

        while (Data.Length > 0)
        //first take two hex value using substring.
        //then  convert Hex value into ascii.
        //then convert ascii value into character.
        {
            Data1 = System.Convert.ToChar(System.Convert.ToUInt32(Data.Substring(0, 2), 16)).ToString();
            sData = sData + Data1;
            Data = Data.Substring(2, Data.Length - 2);
        }
        return sData;
    }
    public string StringToHexadecimal(string Data)
    {
        //first take each charcter using substring.
        //then  convert character into ascii.
        //then convert ascii value into Hex Format

        string sValue;
        string sHex = "";
        foreach (char c in Data.ToCharArray())
        {
            sValue = String.Format("{0:X}", Convert.ToUInt32(c));
            sHex = sHex + sValue;
        }
        return sHex;
    }
}  

Any Ideas?

4

3 に答える 3

1

The problem is that String.Format("{0:X}", Convert.ToUInt32(c)) does not zero-pad its output to two digits, so \r\n becomes DA instead of 0D0A. You'll get a similar problem, but worse, with \t (which becomes 9 instead of 09, which will cause misalignment for subsequent characters as well).

To zero-pad to two digits, you can use X2 instead of bare X; or, more generally, you can use Xn to zero-pad to n digits. (See the "Standard Numeric Format Strings" page on MSDN.)

于 2013-03-12T21:29:56.977 に答える
0

Instead of

System.Convert.ToUInt32(hexString), use

uint.Parse(hexString, System.Globalization.NumberStyles.AllowHexSpecifier);

MSDN says the "AllowHexSpecifier flag indicates that the string to be parsed is always interpreted as a hexadecimal value"

How to: Convert Between Hexadecimal Strings and Numeric Types

于 2013-03-12T21:24:59.153 に答える
-1

the laziest thing you could do is do a string.replace("Ú","\r\n") on the result. Unless there were a compelling reason not to do it this way, I would start here.

Otherwise, in your Char loop, look for the NewLine char and add it as-is to your string.

于 2013-03-12T21:22:10.213 に答える