Reputation: 33
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
e.g. :
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)
What I tried is reading the text file with File.ReadAllText(filename)
but sadly thats in a string Format
not in the byte
format...
We need to convert these text sequence to a byte
array.
These text sequence are actual bytes stored in a text file.
Thanks in Advance..
Upvotes: 2
Views: 697
Reputation: 109567
Try this:
var result =
File.ReadAllText(filename)
.Split(',')
.Select(item => byte.Parse(item.Trim().Substring(2), NumberStyles.AllowHexSpecifier))
.ToArray();
Upvotes: 3
Reputation: 186668
If I understand you right, you have a string
like this
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). 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();
Upvotes: 5