9

I'm trying to convert this string array to byte array.

string[] _str= { "01", "02", "03", "FF"}; to byte[] _Byte = { 0x1, 0x2, 0x3, 0xFF};

I have tried the following code, but it does not work. _Byte = Array.ConvertAll(_str, Byte.Parse);

And also, it would be much better if I could convert the following code directly to the byte array : string s = "00 02 03 FF" to byte[] _Byte = { 0x1, 0x2, 0x3, 0xFF};

Ahmad Hafiz
  • 358
  • 2
  • 6
  • 13

6 Answers6

14

This should work:

byte[] bytes = _str.Select(s => Convert.ToByte(s, 16)).ToArray();

using Convert.ToByte, you can specify the base from which to convert, which, in your case, is 16.

If you have a string separating the values with spaces, you can use String.Split to split it:

string str = "00 02 03 FF"; 
byte[] bytes = str.Split(' ').Select(s => Convert.ToByte(s, 16)).ToArray();
Botz3000
  • 39,020
  • 8
  • 103
  • 127
  • @AhmadHafiz cool :) Also added a solution for converting a string. You can mark my response as answer if it helped you :) – Botz3000 May 10 '12 at 09:42
  • I know this thread is old but I got a problem here. If i convert my string[] to byte[] I get for example [0] "70" string [1] "34" string [2] "0A" string to [0] 112 byte [1] 52 byte [2] 10 byte But I need the same characters as byte. – Noli Jun 13 '12 at 13:22
  • @Noli they **are** the same. "0A" is 10 in hexadecimal notation. It's just displayed in decimal format. The value is correct. – Botz3000 Jun 13 '12 at 13:31
  • Ohhhh that is so.... I spent hours... But thank you sooo much for this!! Thank you! – Noli Jun 13 '12 at 16:34
  • Your code struck with unable to parse... this solution worked fine. https://stackoverflow.com/a/11268578/4425004 – Pranesh Janarthanan Nov 26 '19 at 08:01
4

Try using LINQ:

byte[] _Byte = _str.Select(s => Byte.Parse(s)).ToArray()
Marek Dzikiewicz
  • 2,844
  • 1
  • 22
  • 24
2

With LINQ is the simplest way:

byte[] _Byte = _str.Select(s => Byte.Parse(s, 
                                           NumberStyles.HexNumber,
                                           CultureInfo.InvariantCulture)
                          ).ToArray();

If you have a single string string s = "0002FF"; you can use this answer

Community
  • 1
  • 1
SynerCoder
  • 12,493
  • 4
  • 47
  • 78
1

You can still use Array.ConvertAll if you prefer, but you must specify base 16. So either

_Byte = Array.ConvertAll(_str, s => Byte.Parse(s, NumberStyles.HexNumber));

or

_Byte = Array.ConvertAll(_str, s => Convert.ToByte(s, 16));
Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181
1

If you want to use ConvertAll you could try this:

byte[] _Byte = Array.ConvertAll<string, byte>(
    _str, s => Byte.Parse(s, NumberStyles.AllowHexSpecifier));
Nadir Sampaoli
  • 5,437
  • 4
  • 22
  • 32
0

Try this one:

var bytes = str.Select(s => Byte.Parse(s, NumberStyles.HexNumber)).ToArray();
ie.
  • 5,982
  • 1
  • 29
  • 44