Reputation: 2276
I'm starting with the two values below:
finalString = "38,05,e1,5f,aa,5f,aa,d0";
string[] holder = finalString.Split(',');
I'm looping thru holder like so:
foreach (string item in holder)
{
//concatenate 0x and add the value to a byte array
}
On each iteration I would like to concatenate a 0x to make it a hex value and add it to a byte array.
This is what I want the byte array to be like when I finish the loop:
byte[] c = new byte[]{0x38,0x05,0xe1,0x5f,0xaa,0x5f,0xaa,0xd0};
So far all my attempts have not been successful. Can someone point me in the right direction?
Upvotes: 1
Views: 21740
Reputation: 416131
You can do this as a one-liner:
var c = holder.Select(s => byte.Parse(s, NumberStyles.AllowHexSpecifier)).ToArray();
c
is now a byte array with the data you need.
Upvotes: 4
Reputation: 50028
This will generate the list of byte values based on the comma separated hex values you have:
string hex_numbers = "38,05,e1,5f,aa,5f,aa,d0";
string[] hex_values = hex_numbers.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
byte[] byte_array = new byte[hex_values.Length];
for(int i = 0; i < hex_values.Length; i++)
{
byte_array[i] = byte.Parse(hex_values[i], System.Globalization.NumberStyles.AllowHexSpecifier);
}
Upvotes: 1
Reputation: 7995
You don't have to concatenate the prefix "0x". This prefix is used by the C# compiler when parsing literals, but byte.Parse
doesn't use it
byte[] myByteArray = new byte[holder.Length];
int i = 0;
foreach (string item in holder)
{
myByteArray[i++] = byte.Parse(item, System.Globalization.NumberStyles.AllowHexSpecifier);
}
Upvotes: 6
Reputation: 47809
just create a new byte array which is the size of both arrays put together. Then insert one, and insert the second into the new buffer. array sizes in .net are non-mutable
another approach would be to use something like List, and then just loop through each array and add it
var buffer = new List<byte>();
foreach(var b in firstArray) buffer.Add(b);
foreach(var b2 in secondArray) buffer.Add(b2);
byte[] newArray = buffer.ToArray();
Upvotes: 1