ארכיון

רשומות עם התג ‘Encoding’

System.String is UTF16

26 ספטמבר, 2009 תגובה אחת

והפעם, טיפה Encoding 🙂

תדע כל מתכנתת עבריה: כל string בדוט נט הוא ב encoding של UTF16.

ואגב, זו הסיבה שסיריאליזציה ל XML היא כברירת מחדל UTF16.

"ואם אני רוצה string עם encoding אחר?"

-אין.

אין כזה דבר בדוט נט.

רוצה string? -יש רק ב encoding של UTF16.

רוצה משהו אחר (נניח, UTF32)? יש בייצוגים אחרים של הטקסט: byte array למשל.

הנה קצת קוד:


using System;
using System.Text;
namespace Playing.With.Strings
{
  class Program
  {
    static void Main(string[] args)
    {
      string myText = "hello";

      byte[] asciiBytes = Encoding.ASCII.GetBytes(myText);
      Console.WriteLine("ASCII bytes:");
      Console.WriteLine(ByteArrayToString(asciiBytes));
      Console.WriteLine(Encoding.ASCII.GetString(asciiBytes));

      byte[] unicodeBytes = Encoding.Unicode.GetBytes(myText);
      Console.WriteLine("Unicode bytes:");
      Console.WriteLine(ByteArrayToString(unicodeBytes));
      Console.WriteLine(Encoding.Unicode.GetString(unicodeBytes));

      byte[] utf32Bytes = Encoding.UTF32.GetBytes(myText);
      Console.WriteLine("UTF32 bytes:");
      Console.WriteLine(ByteArrayToString(utf32Bytes));
      Console.WriteLine(Encoding.UTF32.GetString(utf32Bytes));

      Console.WriteLine("done, press *enter* to quit…");
      Console.ReadLine();
    }

    public static string ByteArrayToString(byte[] source)
    {
      StringBuilder sb = new StringBuilder();
      sb.Append("[");
      int sourceLength = source.Length;
      for (int k = 0; k < sourceLength; k++)
      {
        sb.Append(source[k]);
        if (k != sourceLength - 1)
          sb.Append(", ");
      }
      sb.Append("]");
      string result = sb.ToString();
      return result;
    }
  }
}

והתוצאה היא:

ASCII bytes:
[104, 101, 108, 108, 111]
hello
Unicode bytes:
[104, 0, 101, 0, 108, 0, 108, 0, 111, 0]
hello
UTF32 bytes:
[104, 0, 0, 0, 101, 0, 0, 0, 108, 0, 0, 0, 108, 0, 0, 0, 111, 0, 0, 0]
hello
done, press *enter* to quit...

בשורה התחתונה, כדי לייצג טקסט עם encoding אחר, אני בד"כ משתמש ב byte array.

קטגוריות:תכנות תגיות:,
Quantcast