Joe Joe - 1 month ago 4x
C# Question

How to put chars that actually represent hex values in a byte array

I have a string

text = 0a00...4c617374736e6e41
. This string actually contains hex values as chars. What I am trying to do is to the following conversion, without changing e. g. the char

text = 0a...4c617374736e6e41;
--> byte[] bytes = {0x0a, ..., 0x4c, 0x61, 0x73, 0x74, 0x73, 0x6e, 0x6e, 0x41};

This is what I tried to implement so far:

string text = "0a00...4c617374736e6e41";
var storage = StringToByteArray(text)

public static byte[] StringToByteArray(string text)
char[] buffer = new char[text.Length/2];
byte[] bytes = new byte[text.length/2];
using(StringReader sr = new StringReader(text))
int c = 0;
while(c <= text.Length)
sr.Read(buffer, 0, 2);
//How do I store the blocks in the byte array in the needed format?
c +=2;

gives me the two chars I need. But I have NO idea how to put them in the desired format.

Here are some links I already found in the topic, however I were not able to transfer that to my problem:


Try this

            string text = "0a004c617374736e6e41";
            List<byte> output = new List<byte>();
            for (int i = 0; i < text.Length; i += 2)
                output.Add(byte.Parse(text.Substring(i,2), System.Globalization.NumberStyles.HexNumber));