Ahmad Hafiz
Ahmad Hafiz

Reputation: 368

Convert String[] to byte[] array

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};

Upvotes: 9

Views: 35019

Answers (6)

Botz3000
Botz3000

Reputation: 39600

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();

Upvotes: 14

Nadir Sampaoli
Nadir Sampaoli

Reputation: 5555

If you want to use ConvertAll you could try this:

byte[] _Byte = Array.ConvertAll<string, byte>(
    _str, s => Byte.Parse(s, NumberStyles.AllowHexSpecifier));

Upvotes: 1

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61912

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));

Upvotes: 1

ie.
ie.

Reputation: 6101

Try this one:

var bytes = str.Select(s => Byte.Parse(s, NumberStyles.HexNumber)).ToArray();

Upvotes: 0

SynerCoder
SynerCoder

Reputation: 12766

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

Upvotes: 2

Marek Dzikiewicz
Marek Dzikiewicz

Reputation: 2884

Try using LINQ:

byte[] _Byte = _str.Select(s => Byte.Parse(s)).ToArray()

Upvotes: 4

Related Questions