Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

C# array to string

Options
  • 07-08-2011 2:38pm
    #1
    Registered Users 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 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 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 Posts: 375 ✭✭unknownlegend


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

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


  • Registered Users 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 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