0

What would be the best way to turn the following text file of bytes(acii hex format) into a byte array in C#?

C7 40 04 96 96 C9 F3 3F C7 ED
73 9D 3D 89 7D F6 2A 0B 4C 9D D6 82 E1 1F 4F F0
1A 45 4F 35 C7 0C 2B 7F 50 40 AC 79 33 C0 DD 0C
6B D2 9F D4 B6 60 9D 74 34 08 C5 19 92 1B 60 20
62 2A 20 B5 03 D3 2A 1F 39 71 DA F5 EE 78 17 9A
03 CA 3C E7 3E 10 75 C3 0F A5 AD AB C2 1D D6 35
0D C8 FD B2 93 F9 6D 53 C6 67 7E F3 38 CE F6 78
FA F5 0D 22 0B F3 FF 06 A2 51 4B E6 77 D5 49 B4
38 72 E9 0B AB 56 92 6D 25 70 D6 4F 4E 6A EB 39
F9 D2 7C 3B 97 66 35 74 A5 0E C0 1F EE E7 E7 CD
DA FF 41 39 8B F6 18 6E F4 3A 00 AB 2C E8 F9 37
7B 7C ED F4 50 43 F4 B2 F0 7C 39 9F 21 73 CF 7B
DD E0 B5 0E 81 70 4D D1 A8 CD 4F 81 3D DC CA CC
98 47 51 84 0C 00 48 07 0D 57 7B 3F 6A 24 A7 CA
BD E4 FF 67 78 EB F4 0F D7 76 45 65 45 77 E8 30
09 C4 51 DA A2 23 CC BF EE FC 9C 49 64 F5 5B F5
9D 64 77 78 3C E7

So far I have a method that turns it into a string of all these values.

    public string ProcessTextFile(string filepath)
    {
        string sTextFile;
        string[] sDelimeters = { "\r\n" };
        string[] TextFileLines;
        string sOutput;

        using (System.IO.StreamReader sr = new System.IO.StreamReader(filepath))
        {

            sTextFile = sr.ReadToEnd();
            TextFileLines =  sTextFile.Split(sDelimeters, StringSplitOptions.None);
            sOutput = string.Join(" ", TextFileLines);
            sr.Close();
        }

        return sOutput;
    }

1 Answer 1

3

Break the problem down into steps. What do you have now? You have a string of two-digit hex values, separated by spaces and/or newline characters.

string input = "C7 40 04 96 96 C9 F3 3F C7 ED ...";

First, you want to split that string up into the hex values. String.Split sounds like a perfect candidate.

string[] groups = input.Split(new[] {' ', '\n'}, StringSplitOptions.RemoveEmptyEntries);

Next, you want to convert each two-digit hex value into a byte. Byte.Parse should do the trick here.

byte[] ar = groups.Select(s => Byte.Parse(s, NumberStyles.HexNumber)).ToArray();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.