-1

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 + "\r");
                                /*here is where I call the convert method*/
                                corretto = ToHex(originale);
                                Console.WriteLine(corretto + "\r");**
                            }
                        }
                    }
                }
            }
        }
    }
}
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272

2 Answers2

3

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);
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
0

I've got a more straight forward solution for you, to convert your hex data back into string format. I've got sample data in here also:

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.
Marc Johnston
  • 1,276
  • 1
  • 7
  • 16
  • Can you please clarify what exactly you are answering? Question is so unclear that it is hard to reason if your post is related to question at all... Also If OP would need such conversion they would find many questions with similar suggestion already.... – Alexei Levenkov May 13 '15 at 23:11
  • I was right thinking that the issue was the space but I was not knowing how to split and do the conversion like you have done. Execuse me if I've posted all the code, my question was only about the string ToHex() method. – giuseppe loddo May 14 '15 at 20:45