0

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:

Community
  • 1
  • 1
kratsching
  • 75
  • 1
  • 9
  • 1
    And that example byte array looks like it is encoded text. Just be sure to know which character set and encoding the sender chose if you are going to decode it. If the sender has not communicated that information to you then you have a broken contract/failed communication/data loss. – Tom Blodget Aug 29 '16 at 23:19
  • Hey @TomBlodget. Can you give me some further explanation? I still have some issues/problems: The bytestream represents a certain structure. Elements are: `MessageId, MessageLanguage, MessageText`. `Console.WriteLine(Encoding.Unicode.GetChars(ByteArray))` gives me the correct `MessageLanguage = de` and `MessageText = This is sample text`. The console also prints a `?` and a lot of empty spaces. Do you have any hints? I think, if we can resolve this, I will adjust and complete my original question. – kratsching Aug 30 '16 at 07:51
  • You just need to reverse the steps that were used to create the structure in the first place. When it comes to bytes that represent text, you simply use code like in your comment except instead of guessing that the encoding is UTF-16 (`Encoding.Unicode`), you need to use the encoding that you know it is. – Tom Blodget Aug 30 '16 at 10:47

1 Answers1

0

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));
            }
jdweng
  • 33,250
  • 2
  • 15
  • 20