简体   繁体   中英

Converting a “string object” into an array of Int32 and then into an array of Uint32

I have the following object containing a string that I wish to convert into an Array of Int32[]:

object stringObject= "4194304 4286147 4380001 4475911 4573920 4674076 4776425 4881015 4987896 5097116 5208729 5322785 5439339 5558445 5680159 5804538 5931641 6061527 6194257 6329894 6468501 6610142 6754886 6902798 7053950 7208411 7366255 7527555 7692387 7860828 8032958 8208857 8761011 9122297 9473110 9814040 10145628 10468373 10782733 11089135 11387970 11679603 11964374 12242598 12514569 12780563 13040835 13295628 13545167 13789664 14029319 14264321 14494846 14721062 14943127 15161191 15375395 15585873 15792753 15996157 16196198 16392986 16586625 16777215"

What I have done (not sure it is the best approach?):

int[] retValues = stringObject.Split(' ').Select(v => Convert.ToInt32(v, 10)).ToArray();

No problem here, but then how to convert this retValues into an array of Uint32[]. I tried the following, but does not work:

uint[] retValuesUint = retValues.Select(v => Convert.ToUInt32(v, 10));

or

uint[] retValuesUint = retValues.Select(v => (UInt32)v);

First of all, your sample doesn't compile, because object has no Split method.

Secondly, if you change the declaration of stringObject to be of type string , the retValues is an array of int s with 64 int s in it . Its length is 64, the objects inside are still int , which is an alias for Int32 .

Console.WriteLine(retValues.Length);
> 64
Console.WriteLine(retValues[0].GetType().Name);
> Int32

EDIT:

There are two problems with the uint conversion you've provided.

  1. ToUInt32 does not accept an int fromBase parameter like ToInt32 does - it will only work with base10 numbers.

  2. You've forgotten the ToArray call at the end, to actually make the uint[] you want.

uint[] retValuesUint = retValues.Select(v => Convert.ToUInt32(v)).ToArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM