Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

C# array to string

  • 07-08-2011 02:38PM
    #1
    Registered Users, Registered Users 2 Posts: 377 ✭✭


    i have a byte array in C#. Is there a function to convert this to a string?
    For example

    buffer[0] = 2;
    buffer[1] = 8;
    buffer[2] = 3;

    Is there a function that will convert that to the string '283'


Comments

  • Registered Users, Registered Users 2 Posts: 234 ✭✭themadhair


    This might help:
    http://www.cprogramming.com/tutorial/string.html

    I imagine you can do something along these lines. Set string1 = buffer[0]. Set string2 = buffer[1]. Then set string1 = string1 + string2. Then set string2 = buffer[2]. Then set string1 = string1 + string2. Repeat until the buffer is exhausted.

    Should be possible to do a for loop for this if you can get the + operator to work as described in the above link.


  • Registered Users, Registered Users 2 Posts: 297 ✭✭stesh


    A nice-looking way to do it with linq would be something like
    byte[] buffer = new byte[] {2,8,3};
    string n = String.Join("", buffer.Select(x => x.ToString()).ToArray());
    

    or in .NET 4.0 just
    byte[] buffer = new byte[] {2,8,3};
    string n = String.Join("", buffer.Select(x => x.ToString()));
    

    alternatively if buffer were really really big a StringBuilder would be more efficient:
    byte[] buffer = new byte[] {1,2,3};
    var sb = new StringBuilder();
    foreach (var x in buffer) sb.Append(x);
    string n = sb.ToString();
    


  • Registered Users, Registered Users 2 Posts: 356 ✭✭unknownlegend


    I'd do:
    Encoding.ASCII.GetString(array);
    

    Or replace ASCII with whatever target encoding you're working with.


  • Registered Users, Registered Users 2 Posts: 2,781 ✭✭✭amen


    [PHP]buffer[0] = 2;
    buffer[1] = 8;
    buffer[2] = 3;

    Is there a function that will convert that to the string '283' [/PHP]

    why do you want to do this ?


  • Registered Users, Registered Users 2 Posts: 1,311 ✭✭✭Procasinator


    stesh wrote: »
    or in .NET 4.0 just
    byte[] buffer = new byte[] {2,8,3};
    string n = String.Join("", buffer.Select(x => x.ToString()));
    

    I think in .NET 4.0 you have string.Join(string, object[]), meaning you can just pass buffer directly in.

    http://msdn.microsoft.com/en-us/library/dd988350.aspx


  • Advertisement
Advertisement