1

I have a string with byte format in it as below

var string="22-74-68-64-62-32-75-74-71-53-5A-6D-44-32-65-61-38-39-43-6A-39-4A-41-3D-3D-22"

Convert this to byte array as

byte[] arr=[22-74-68-64-62-32-75-74-71-53-5A-6D-44-32-65-61-38-39-43-6A-39-4A-41-3D-3D-22]
1
  • If one of these answers solves your problem, best mark one as accepted for future readers Commented Feb 10, 2020 at 23:56

3 Answers 3

3

Slightly more succinct with Convert.ToByte

var bytes = input.Split('-')
                 .Select(x => Convert.ToByte(x,16))
                 .ToArray();

Additional resources

ToByte(String, Int32)

Converts the string representation of a number in a specified base to an equivalent 8-bit unsigned integer.

Sign up to request clarification or add additional context in comments.

Comments

2
using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        string input = "22-74-68-64-62-32-75-74-71-53-5A-6D-44-32-65-61-38-39-43-6A-39-4A-41-3D-3D-22";

        //Split string by '-'
        string[] spl = input.Split('-');

        //Parse bytes and add them to a list
        List<byte> buf = new List<byte>();
        foreach(string s in spl) {
            buf.Add(byte.Parse(s, System.Globalization.NumberStyles.HexNumber));
        }

        //Convert list to byte[]
        byte[] bytes = buf.ToArray();

        //Print byte[] into console
        foreach(byte b in bytes)
            Console.WriteLine(b.ToString("X2"));
    }
}

DotNetFiddle

The above code will cause an exception if the input is not a perfect string of bytes delimited by dashes. If you're not expecting a perfect input you'll have to use byte.TryParse like so:

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        string input = "22-74-68-64-62-32-75-74-71-53-5A-XX-wrgererh-6D-44-32-65-61-38-39-43-6A-39-4A-41-3D-3D-22";

        //Split string by '-'
        string[] spl = input.Split('-');

        //Parse bytes and add them to a list
        List<byte> buf = new List<byte>();
        byte tb;
        foreach(string s in spl) {
            if(byte.TryParse(s, System.Globalization.NumberStyles.HexNumber, null, out tb))
                buf.Add(tb);
        }

        //Convert list to byte[]
        byte[] bytes = buf.ToArray();

        //Print byte[] into console
        foreach(byte b in bytes)
            Console.WriteLine(b.ToString("X2"));
    }
}

DotNetFiddle

Comments

2

You can use Linq to get it quite tidy

byte[] arr = input.Split('-').Select(i => byte.Parse(i, System.Globalization.NumberStyles.HexNumber)).ToArray();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.