Search code examples
c#arrayshexbytetext-parsing

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

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


Solution

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