开发者

Encoding.ASCII.GetString() in Windows Phone Platform

开发者 https://www.devze.com 2023-04-12 12:50 出处:网络
byte[] tagData = GetTagBytes(tagID, out tiffDataType, out numberOfComponents); string str = Encoding.ASCII.GetString(tagData);
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 开发者_JS百科convert string to byte[], now I need to convert byte[] into string.

Any Help would be nice~


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()
    );
}


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


Convert.ToBase64String Method (byte[]) returns string

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

I hope this helps!


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号