Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i convert a string into byte[] of unsigned int 32 C#

Tags:

arrays

c#

I have a string like "0x5D, 0x50, 0x68, 0xBE, 0xC9, 0xB3, 0x84, 0xFF". I want to convert it into:

byte[] key= new byte[] { 0x5D, 0x50, 0x68, 0xBE, 0xC9, 0xB3, 0x84, 0xFF};

I thought about splitting the string by , then loop on it and setvalue into another byte[] in index of i

string Key = "0x5D, 0x50, 0x68, 0xBE, 0xC9, 0xB3, 0x84, 0xFF";

    string[] arr = Key.Split(',');
    byte[] keybyte= new byte[8];
    for (int i = 0; i < arr.Length; i++)
    {
         keybyte.SetValue(Int32.Parse(arr[i].ToString()), i);
    }

but seems like it doesn't work. I get error in converting the string into unsigned int32 on the first beginning.

any help would be appreciated

like image 612
Miroo Avatar asked Feb 27 '23 23:02

Miroo


2 Answers

You can do like this:

byte[] data =
  Key
  .Split(new string[]{", "}, StringSplitOptions.None)
  .Select(s => Byte.Parse(s.Substring(2), NumberStyles.HexNumber))
  .ToArray();
like image 50
Guffa Avatar answered Mar 15 '23 06:03

Guffa


keybyte[i] = byte.Parse(arr[i].Trim().Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
like image 22
Itay Karo Avatar answered Mar 15 '23 07:03

Itay Karo