[英]How to convert a text file having a hexadecimal code sequence into a byte array?
So I was wondering if there any possibility to read a plain text bytes sequence in hexadecimal from a text file?所以我想知道是否有可能从文本文件中读取十六进制的纯文本字节序列?
The Bytes Are Saved On to A Text File in Text Format字节以文本格式保存到文本文件中
eg :例如:
string text =
@"0x4D, 0x5A, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
0xFF, 0xFF, 0x00, 0x00, 0xB8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00";
Here I don't mean File.ReadAllBytes(filename)
这里我不是指
File.ReadAllBytes(filename)
What I tried is reading the text file with File.ReadAllText(filename)
but sadly thats in a string Format
not in the byte
format...我尝试的是使用
File.ReadAllText(filename)
读取文本文件,但遗憾的是,这是字符串Format
而不是byte
格式...
We need to convert these text sequence to a byte
array.我们需要将这些文本序列转换为
byte
数组。
These text sequence are actual bytes stored in a text file.这些文本序列是存储在文本文件中的实际字节。
Thanks in Advance..提前致谢..
If I understand you right, you have a string
like this如果我理解正确,你有一个这样的
string
string text =
@"0x4D, 0x5A, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
0xFF, 0xFF, 0x00, 0x00, 0xB8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00";
and you want to obtain byte[]
(array).并且您想获得
byte[]
(数组)。 If it's your case, you can try matching with a help of regular expressions :如果是您的情况,您可以尝试在正则表达式的帮助下进行匹配:
using System.Linq;
using System.Text.RegularExpressions;
...
byte[] result = Regex
.Matches(text, @"0x[0-9a-fA-F]{1,2}") // 0xH or 0xHH where H is a hex digit
.Cast<Match>()
.Select(m => Convert.ToByte(m.Value, 16)) // convert each match to byte
.ToArray();
Try this:尝试这个:
var result =
File.ReadAllText(filename)
.Split(',')
.Select(item => byte.Parse(item.Trim().Substring(2), NumberStyles.AllowHexSpecifier))
.ToArray();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.