Home > OS >  C# convert hex string to uint array
C# convert hex string to uint array

Time:02-16

I have a body of text that is innertext inside of an XML. Here are 3 lines of that string for example

0x2007A3C8,0xAE8900B8,
0x2007A3CC,0x000E5320,
0x2007A3D0,0x03E00008

So the innertext property is a string. I am trying to convert this entire string back into an uint array. So that for every comma adds a new array element.

x , x
x , x

Would be a total of 4 array elements.

I want to keep the hex syntax, everything. I just need this back into an uint array. Any ideas?

CodePudding user response:

It should be as simple as this:

string input = "0x2007A3C8,0xAE8900B8, 0x2007A3CC,0x000E5320, 0x2007A3D0,0x03E00008";
string[] strNumbers = input.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
uint[] numbers =  Array.ConvertAll(strNumbers, z => Convert.ToUInt32(z.Trim(), 16));

CodePudding user response:

I'd definitely propose using LINQ for that:

var initialString = "0x2007A3C8,0xAE8900B8,\n0x2007A3CC,0x000E5320,\n0x2007A3D0,0x03E00008";
var unsignedValues = initialString
                            .Split(',')
                            .Select(n => Convert.ToUInt32(n.Trim(), 16));

Don't really understand about "keeping the hex syntax", but you can sustain it like this, I guess:

var initialString = "0x2007A3C8,0xAE8900B8,\n0x2007A3CC,0x000E5320,\n0x2007A3D0,0x03E00008";
var unsignedValues = initialString
                            .Split(',')
                            .Select(n => "0x"   Convert.ToUInt32(n.Trim(),16));
  •  Tags:  
  • c#
  • Related