简体   繁体   中英

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)

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..

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

Try this:

var result = 
    File.ReadAllText(filename)
   .Split(',')
   .Select(item => byte.Parse(item.Trim().Substring(2), NumberStyles.AllowHexSpecifier))
   .ToArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM