我正在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");**
}
}
}
}
}
}
}
}
您有将十六进制字节转换为实际字节的正确想法,但是您的方法无效。假设您要传递以空格分隔的有效十六进制字节序列,则可以在您的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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句