将ASCII转换为HEX保持换行符

时间:2013-03-12 21:14:56

标签: c# .net hex ascii

好的,所以我正在制作一个ASCII到十六进制转换器并且它工作正常,但是当我插入换行符时,它会用这个字符替换它们 - > Ú


转过来

  

1
  2
  3

到这个

  

1Ú2Ú3

命令按钮下的代码

    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);
    }

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;
    }
}  

任何想法?

3 个答案:

答案 0 :(得分:1)

问题是String.Format("{0:X}", Convert.ToUInt32(c))没有将其输出零填充为两位数,因此\r\n变为DA而不是0D0A。你会遇到类似的问题,但更糟糕的是\t9而不是09,这会导致后续字符错位。“

要将零填充到两位数,您可以使用X2代替裸X;或者,更一般地说,您可以使用Xn将零填充到 n 位。 (见the "Standard Numeric Format Strings" page on MSDN。)

答案 1 :(得分:0)

而不是

System.Convert.ToUInt32(hexString),使用

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

MSDN说"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

答案 2 :(得分:-1)

你能做的最懒的事情就是对结果做string.replace("Ú","\r\n")。除非有令人信服的理由不这样做,否则我会从这里开始。

否则,在Char循环中,查找NewLine char并将其按原样添加到字符串中。