c#将字符串hex转换为ascii?从csv文件中读取字符串

时间:2015-05-13 22:43:59

标签: c# string hex

我尝试使用C#和visual studio express来转换包含ASCII字中十六进制数据名称的很长字符串

示例:我读取的文件列包含字符串

  

4E 4F 54 49 46 59 ..................(继续)

这意味着在ASCI" NOTIFY"

我的程序在使用ToHex方法时遇到此异常,我尝试转换它。

为什么会出现此异常?它是由十六进制ASCII值的每两个字符之间的空格字符引起的吗?

  

类型' System.FormatException'的第一次机会异常发生在   mscorlib.dll类型
的第一次机会异常   ' System.Reflection.TargetInvocationException'发生在mscorlib.dll中   类型
的第一次机会例外   ' System.Reflection.TargetInvocationException'发生在mscorlib.dll

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.IO;
using LumenWorks.Framework.IO;
using LumenWorks.Framework.IO.Csv;

//main class
namespace WpfApplication2
{
    public partial class MainWindow : Window
    {
        public String FirstName { get; set; }

        public MainWindow()
        {
            InitializeComponent();
            ConvertTrace.HexUtf8toAsci();
        }
    }

    //convert service classe
    public class ConvertTrace
    {
        public static String output;
        public static String fine;
        /*this is the method for convert the string that contain the hex spaced couples of chars into a asci readable string*/

        public static string ToHex(String hexString)
        {
            byte[] dBytes = Enumerable.Range(0, hexString.Length).Where(x => x % 2 == 0).Select(x => Convert.ToByte(hexString.Substring(x, 2), 16)).ToArray();

            output = System.Text.Encoding.ASCII.GetString(dBytes);
            return output;
        }

        public static void HexUtf8toAsci()
        {
            // open the file "data.csv" which is a CSV file with headers
            using (CsvReader csv = new CsvReader(new StreamReader("test3pulito.csv"), true))
            {
                int fieldCount = csv.FieldCount;
                string[] headers = csv.GetFieldHeaders();
                while (csv.ReadNextRecord())
                {
                    for (int i = 0; i < fieldCount; i++)
                    {
                        string line2 = null;
                        int line_number2 = 0;
                        using (StreamWriter writer2 = new StreamWriter("test3new.csv"))
                        {
                            System.Text.UTF8Encoding encoding;
                            byte[] dBytes;
                            string ASCIIresult;
                            string utf8result;
                            string corretto;
                            string originale;
                            string risultato;
                            line_number2++;
                            //here I check the column of the file where to get the string to convert
                            if (i>7)
                            {
                                originale = csv[i];
                                Console.WriteLine(originale + "\r");
                                /*here is where I call the convert method*/
                                corretto = ToHex(originale);
                                Console.WriteLine(corretto + "\r");**
                            }
                        }
                    }
                }
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您有正确的想法将十六进制字节转换为实际字节,但您的方法不起作用。假设您传递的是一系列空格分隔的有效十六进制字节,您可以在ToHex()方法中执行此操作:

var hexBytes = "4E 4F 54 49 46 59";
var bytes = hexBytes.Split(' ')
    .Select(hb => Convert.ToByte(hb, 16)) // converts string -> byte using base 16
    .ToArray();
var asciiStr = System.Text.Encoding.ASCII.GetString(bytes);

答案 1 :(得分:0)

我有一个更直接的解决方案,将十六进制数据转换回字符串格式。我在这里也有样本数据:

string s = "4E 4F 54 49 46 59"; // Sample data
string hex = "0123456789ABCDEF";
string[] tokens = s.Split(' ');
StringBuilder sb = new StringBuilder();
foreach (string token in tokens)
    sb.Append((char)(hex.IndexOf(token[0]) * 16 + hex.IndexOf(token[1])));
string output = sb.ToString(); // The variable output contains your converted text.