简体   繁体   中英

Convert int array to string in C#

I have an int[] :

RXBuffer[0], RXBuffer[1],..., RXBuffer[9]

where each value represents an ASCII code, so 0x31 represents 1 , 0x41 represents A .

How do I convert this to a 10 character string ?

So far I've tried Data = RxBuffer.ToString(); . But it shows Data equals to System.Int32[] which is not what my data is.

How can I do this?

Assuming the "int array" is values in the 0-9 range (which is the only way that makes sense to convert an "int array" length 10 to a 10-character string) - a bit of an exotic way:

string s = new string(Array.ConvertAll(RXBuffer, x => (char)('0' + x)));

But pretty efficient (the char[] is right-sized automatically, and the string conversion is done just with math, instead of ToString() ).


Edit: with the revision that makes it clear that these are actually ASCII codes, it becomes simpler:

string s = new string(Array.ConvertAll(RXBuffer, x => (char)x));

Although frankly, if the values are ASCII (or even unicode) it would be better to store it as a char[] ; this covers the same range, takes half the space, and is just:

string s = new string(RXBuffer);

LolCoder All you need is :

string.Join("",RXBuffer);

============== Or =================

        int[] RXBuffer = {0,1,2,3,4,5,6,7,8,9};
        string result  =  string.Join(",",RXBuffer);

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