문제

I need help with convert numbers from byte array to string in C#.

There is my code:

string Astr = "123456789";
byte[] AByte = Astr.Select(c => (byte)(c - '0')).ToArray(); 
Astr = AByte.ToString(); // This is problem - I need convert numbers back to string

Thank you for yours ideas :)

도움이 되었습니까?

해결책

What about this,

Astr = new String(AByte.Select (b=>(Char)(b+ 48)).ToArray())

다른 팁

var answer = string.Concat(AByte);

The overload used was new in .NET 4.0 (2010).

This works only if all values in the array are in the range (byte)0 through (byte)9. As pointed out in the comments, nine string instances will be created. However, no lambda (anonymous function) or intermediate array is used.

A reasonably efficient approach would be to use the String constructor that takes a char array. Then you simply need to use Select to map your values into the original char values, and call ToArray().

string originalString = new String(AByte.Select(x => (char)(x + '0')).ToArray());

This question and answer suggests that using a StringBuilder in a loop could be marginally faster, however, I don't think it's worth it unless you know you have a bottleneck.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top