locked
Byte array to String in C#

    Question

  •  

    Hi,

     

    When I am converting Byte Array to String, the swedish characters are converting into some symbols. Is there  anyway to solve this issue?

     

    ÅÅkale is converting into CCKale if i use the code like: System.Text.Encoding.ASCII.GetString(bytearray)

     

    Any suggestions?

     

    Thanks

    Shaa

    Thursday, January 24, 2008 8:30 AM

Answers

  • Hi,

    First you just need to convert your bytes to something more useful, like UTF8 for example, and then you can get you string from it.
    Something like (in my case: iso-8859-1):

                    buf = Encoding.Convert(Encoding.GetEncoding("iso-8859-1"), Encoding.UTF8, buf);
                    tempString = Encoding.UTF8.GetString(buf, 0, count);

    Cheers,
    Miroslav
    Tuesday, February 12, 2008 10:59 PM

All replies

  • You could use the "Default" encoding instead of ASCII.

    You can test it with this:

    string test = System.Text.Encoding.Default.GetString(
                    System.Text.Encoding.Default.GetBytes("ÅåÄäÖö"));

    versus

    string test = System.Text.Encoding.ASCII.GetString(
                    System.Text.Encoding.ASCII.GetBytes("ÅåÄäÖö"));

    The first one converts the scandics and the second doesen't. The ASCII character set does not contain the scands you know, the ASCII encoding in .NET is 7-bit according the documentation. You can use for example UTF8 if you need to use a fixed encoding instead of the Default one.
    • Proposed as answer by Doug Domeny Friday, March 09, 2012 4:51 PM
    Thursday, January 24, 2008 8:46 AM
  • Check out the Convert class.  Look for the ToBase64CharArray Method and the FromBase64CharArray Method to start.  There are similar methods that convert bytes to and from string types.

     

    Rudedog

     

    Thursday, January 24, 2008 2:00 PM
  • Hi,

    First you just need to convert your bytes to something more useful, like UTF8 for example, and then you can get you string from it.
    Something like (in my case: iso-8859-1):

                    buf = Encoding.Convert(Encoding.GetEncoding("iso-8859-1"), Encoding.UTF8, buf);
                    tempString = Encoding.UTF8.GetString(buf, 0, count);

    Cheers,
    Miroslav
    Tuesday, February 12, 2008 10:59 PM
  • I found code at the URL  http://poshcode.org/417 helpful. It has a line on how to infer encoding of a text and use it to properly convert byte array to appropriate characters:

    $encoding = [System.Text.Encoding]::GetEncoding( $stream.CharacterSet )
    ## read chunk
    $encoding.GetString($buffer,0,$chunk_length)

    Miron
    Wednesday, December 23, 2009 10:56 AM
  • Thanks a lot.

    This helped me.

    Friday, July 15, 2011 1:57 PM