0

I haven't found a solution for this yet and I'm getting a headache... D:

Now lets say I have a string as:

string n = "74657374";

I want to convert that into a byte array.

byte[] { 0x74, 0x65, 0x73, 0x74 }; //how I want it like

What's the best way going about this?

user1594121
  • 107
  • 1
  • 8

3 Answers3

1

Try this:

public static byte[] GetNumbers(string data)
{
    if (data == null) throw new ArgumentNullException();
    if (data.Length % 2 != 0
           || !data.All(char.IsDigit)) throw new ArgumentException();
    List<byte> temp = new List<byte>(data.Length / 2);
    for (int i = 0; i < data.Length; i += 2)
    {
        temp.Add(byte.Parse(string.Concat(data[i], data[i + 1]),
            NumberStyles.HexNumber));
    }
    return temp.ToArray();
}

And also, if the string might not be formatted properly, use this (it's just the same thing, except in the TryX format):

public static bool TryGetNumbers(string data, out byte[] output)
{
    if (data == null || data.Length % 2 != 0 || !data.All(char.IsDigit))
    {
        output = null;
        return false;
    }
    List<byte> temp = new List<byte>(data.Length / 2);
    for (int i = 0; i < data.Length; i += 2)
    {
        temp.Add(byte.Parse(string.Concat(data[i], data[i + 1]),
            NumberStyles.HexNumber));
    }
    output = temp.ToArray();
    return false;
}
It'sNotALie.
  • 22,289
  • 12
  • 68
  • 103
  • I think all errors are fixed... testing it now. – It'sNotALie. Jun 08 '13 at 10:20
  • @walkhard Just copied it into VS, fixing those now. – It'sNotALie. Jun 08 '13 at 10:21
  • There's no point in adding an answer here - the question is an exact dupe, it will be closed soon. Adding a new answer to the original question may give you better visibility. – Sergey Kalinichenko Jun 08 '13 at 10:22
  • @dasblinkenlight Will add it then. – It'sNotALie. Jun 08 '13 at 10:23
  • @NikolaMitev Yes it will, as it's a `Func`! Don't downvote because you don't know what you're doing. How do I know it compiles? **Because I've compiled it myself.** Also did you see the `!` sign before `.All`? It means logical not, so if they all meet the criteria it returns false, else it returns true. It **does** work, it's more efficient as it doesn't use equality. So please run it through an actual compiler before spouting out nonsense. – It'sNotALie. Jun 08 '13 at 10:41
0

If you define an extension method to split your sequence into subsequences of a given size, such as Handcraftsman's InSetsOf, you could do it as a one-liner:

string n = "74657374";
byte[] b = n.InSetsOf(2)
            .Select(x => (byte)((x[0] - '0') * 16 + x[1] - '0'))
            .ToArray();

This code assumes that the length of your string is even.

Community
  • 1
  • 1
Douglas
  • 53,759
  • 13
  • 140
  • 188
0

Here's an alternative method, leveraging the char[] as an IEnumerable<char>:

    static byte[] ToArrayOfByteValues(this string str)
    {
        var charArray = str.ToArray();
        var byteArray = new byte[charArray.Length / 2];

        for (int i = 0; i < byteArray.Length; i++)
        {
            var q = new StringBuilder().Append(charArray.Skip(i * 2).Take(2).ToArray<char>()).ToString();
            byteArray[i] = Byte.Parse(q, System.Globalization.NumberStyles.HexNumber);
        }

        return byteArray;
    }
Theodoros Chatzigiannakis
  • 28,773
  • 8
  • 68
  • 104