2
byte[] tagData = GetTagBytes(tagID, out tiffDataType, out numberOfComponents);
string str = Encoding.ASCII.GetString(tagData);

With windows phone platform, the framework doesn't support Encoding.ASCII.GetString() method.

I used to get help from Passant's post ASCIIEncoding In Windows Phone 7 befroe. But it only convert string to byte[], now I need to convert byte[] into string.

Any Help would be nice~

Community
  • 1
  • 1
lavandachen
  • 75
  • 2
  • 5
  • 1
    Are you sure you REALLY need ASCII? 90% of the users that ask ASCII really want UTF-8 – xanatos Oct 13 '11 at 07:41
  • Does [this answer](http://stackoverflow.com/a/9858196/1028230) not work? You should/might (?) have a `GetString(Byte[], Int32, Int32)` method where you can use `GetString(tagData, 0, tagData.Length)`, correct? – ruffin Sep 20 '14 at 17:51

4 Answers4

3

If you try to understand how Hans' code works, you'll easily come up with the reverse conversion:

public static string AsciiToString(byte[] bytes) { 
        StringBuilder sb = new StringBuilder(bytes.Length); 
        foreach(byte b in bytes) {
            sb.Append(b<=0x7f ? (char)b : '?'); 
        } 
        return sb.ToString(); 
    } 

You can also use LINQ but a nice solution is available only on .NET 4.0:

string AsciiToString(byte[] bytes)
{
  return string.Concat( bytes.Select(b => b <= 0x7f ? (char)b : '?') );
}

The unfortunate lack of the String.Concat<T>(IEnumerable<T>) overload in former versions of the framework forces you to use the somewhat ugly and inefficient:

string AsciiToString(byte[] bytes)
{
  return string.Concat( 
    ( bytes.Select(b => (b <= 0x7f ? (char)b : '?').ToString()) )
    .ToArray()
    );
}
Community
  • 1
  • 1
Serge Wautier
  • 21,494
  • 13
  • 69
  • 110
0

Based on Serge - appTranslator, I created an overloaded implementation that fully mimics Encoding.ASCII.GetString for silverlight

    public static string EncodingASCIIGetString(byte[] bytes, int index, int count)
    {
        StringBuilder sb = new StringBuilder(count);

        for(int i = index; i<(index+count); i++)
        {
            sb.Append(bytes[i] <= 0x7f ? (char)bytes[i] : '?');             
        }

        return sb.ToString();
    }

Havent tried it though. Feel free to edit

Syaiful Nizam Yahya
  • 4,196
  • 11
  • 51
  • 71
0

If you really have ASCII (so <= 7f) you can simply cast the single bytes as char.

StringBuilder sb = new StringBuilder(tagData.Length);
foreach (var b in tagData)
{
    sb.Append((char)b);
}

var str = sb.ToString();

I'll add that probably what you need is Encoding.UTF8.GetString(tagData) :-)

xanatos
  • 109,618
  • 12
  • 197
  • 280
0

Convert.ToBase64String Method (byte[]) returns string

http://msdn.microsoft.com/en-us/library/dhx0d524(VS.95).aspx

I hope this helps!

flacnut
  • 1,030
  • 4
  • 11
  • 21