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?

0

3 Answers 3

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;
}
Sign up to request clarification or add additional context in comments.

5 Comments

I think all errors are fixed... testing it now.
@walkhard Just copied it into VS, fixing those now.
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.
@dasblinkenlight Will add it then.
@NikolaMitev Yes it will, as it's a Func<char, bool>! 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.
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;
    }

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.