Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Bytes String to Bytes Array

Tags:

arrays

c#

byte

I have following string of bytes

17 80 41 00 01 00 01 00 08 00 44 61 72 65 46 61 74 65 01 00 00 00 01 00 03 00 01 00 09 00 43 68 61 6E 6E 65 6C 2D 31 00 00 02 00 09 00 43 68 61 6E 6E 65 6C 2D 32 65 00 03 00 09 00 43 68 61 6E 6E 65 6C 2D 33 65 00

What is the best way to take it as input from user and make it into byte array?

like image 254
jM2.me Avatar asked Feb 22 '11 01:02

jM2.me


2 Answers

Try:

string text = ...
byte[] bytes = text.Split()
                   .Select(t => byte.Parse(t, NumberStyles.AllowHexSpecifier))
                   .ToArray();

If you want to only split on the space-character (rather than any whitespace) use Split (' ').

like image 190
Ani Avatar answered Oct 27 '22 00:10

Ani


If the user is inputting it into the command line just like that, do this:

        string input = GetInput(); // this is where you get the input
        string[] numbs = input.Split(' ');
        byte[] array = new byte[numbs.Length];
        int i = 0;

        foreach (var numb in numbs)
        {
            array[i++] = byte.Parse(numb, NumberStyles.HexNumber);
        }
like image 22
joe_coolish Avatar answered Oct 26 '22 23:10

joe_coolish