开发者

C# - Converting string data to actual string representation

I have a device that sends out string data representing its settings, bu开发者_开发问答t the data is encoded in the string as its unicode(?) representation. For example, the device sends the string "00530079007300740065006D" which represents the string "System". Are there function built into C# that will convert the string data sent from the device to the actual string? If not, can someone advise me on how best to perform this conversion?


Totally jumping on @Will Dean's solution bandwagon here (so dont mark me as the answer).

If you're using Will's solution alot, I suggest wrapping it into a string extension:

public static class StringExtensions
{
    public static string HexToString(this string input)
    {
        return new String(Enumerable.Range(0, input.Length/4)
                              .Select(idx => (char) int.Parse(input.Substring(idx*4,4),
                                                              NumberStyles.HexNumber)).ToArray());
    }
}


This isn't a built-in function, but it is only one line of code:

string input = "00530079007300740065006D";

String output = new String(Enumerable.Range(0, input.Length/4)
     .Select(idx => (char)int.Parse(input.Substring(idx *  4,4),
           NumberStyles.HexNumber)).ToArray());

Here's another one, which is perhaps a little more high-minded in not doing the hacky char/int cast:

string out2 =
   Encoding.BigEndianUnicode.GetString(Enumerable.Range(0, input.Length/2)
     .Select(idx => byte.Parse(input.Substring(idx * 2, 2),
          NumberStyles.HexNumber)).ToArray());


Yes, .NET has a built in way to move from a given encoding type to another type, say UTF8 -> ASCII or somesuch. The namespace you'll need is System.Text.Encoding.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜