Pregunta

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 :)

¿Fue útil?

Solución

What about this,

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

Otros consejos

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top