Joe Joe - 3 months ago 8
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
a
to
0x41
;

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)
...
Console.ReadKey();

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);
Console.WriteLine(buffer);
//How do I store the blocks in the byte array in the needed format?
c +=2;
}
}
}


The
Console.WriteLine(buffer)
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:


Answer

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));
            }
Comments