Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

c# convert a string hex to ascii ? string reading from a csv file

I'm trying in C# and visual studio express to convert a very long string of chars that contains hex data names in ASCII words

Example : The file column that I read contain the string

4E 4F 54 49 46 59 .................. (continue)

that means in ASCI "NOTIFY"

My program is getting this exception when with the method ToHex I try to convert this.

Why appear this exception? Is it caused by the char of space between each two chars of hex ASCII values?

A first chance exception of type 'System.FormatException' occurred in mscorlib.dll A first chance exception of type
'System.Reflection.TargetInvocationException' occurred in mscorlib.dll A first chance exception of type
'System.Reflection.TargetInvocationException' occurred in 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 + "
");
                                /*here is where I call the convert method*/
                                corretto = ToHex(originale);
                                Console.WriteLine(corretto + "
");**
                            }
                        }
                    }
                }
            }
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You had the right idea to convert the hex bytes to actual bytes but your approach doesn't work. Assuming that you're passing in a sequence of valid hex bytes that are space separated, you could do this in your ToHex() method:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...