C# 常用數據類型轉換(一)

1. 數值類型之間的相互轉換
數值類型包括 byte, short, int, long, fload, double 等,根據這個排列順序,各種類型的值依次可以向後自動進行轉換。
如下例:

namespace ConsoleApplicationTest
{
    class Program
    {
        static void Main(string[] args)
        {
            byte   a = 1; 
            short  b = a; 
            int    c = b;
            long   d = c; 
            float  e = d; 
            double f = e;

            Console.WriteLine("byte a = " + a.ToString());
            Console.WriteLine("short b = " + b.ToString());
            Console.WriteLine("int c = " + c.ToString());
            Console.WriteLine("long d = " + d.ToString());
            Console.WriteLine("float e = " + e.ToString());
            Console.WriteLine("double f = " + f.ToString());
            Console.ReadLine();
        }
    }
}

譯順利通過,運行結果是各變量的值均爲 1;當然,它們的類型分別還是 System.Byte 型……System.Double 型。現在我們來試試,如果把賦值的順序反過來會怎麼樣呢?

        static void Main(string[] args)
        {
            int g = 1;
            short h = g; // 編譯錯誤

            // 這是使用強制類型轉換
            short g1 = 1;
            byte h1 = (byte)g1; // 將 short 型的 g 的值強制轉換成 short 型後再賦給變量 h
            Console.WriteLine("byte h1 = " + h1.ToString()); // 輸出 byte h1 = 1

            Console.ReadLine();
        }

但是,如果我們使用強制轉換,就不得不再考慮一個問題:short 型的範圍是 -32768 ~ 23767,而 byte 型的範圍是 0 ~ 255,那麼,如果變量 g 的大小超過了 byte 型的範圍又會出現什麼樣的情況呢?

        static void Main(string[] args)
        {
            short a = 300;
            byte b = (byte)a;

            Console.WriteLine("byte b = " + b.ToString()); // 輸出 byte b = 44

            Console.ReadLine();
        }

在進行轉換的時候,應當注意被轉換的數據不能超出目標類型的範圍。這不僅體現在多字節數據類型(相對,如上例的 short) 轉換爲少字節類型(相對,如上例的 byte) 時,也體現在字節數相同的有符號類型和無符號類型之間,如將 byte 的 129 轉換爲 sbyte 就會溢出。

decimal類型
在C#裏是表示 128 位數據類型。double相比,decimal 類型具有更高的精度和更小的範圍,它適合於財務和貨幣計算。
decimal:
有效位:±1.0 × 10(-28次方) 到 ±7.9 × 10(28次方) 精度:28 到 29 位 double: 有效位:±5.0 × 10(-324次方) 到 ±1.7 × 10(308次方) 精度:15 到 16 位

2. 字符的 ASCII 碼和 Unicode 碼
很多時候我們需要得到一個英文字符的 ASCII 碼,或者一個漢字字符的 Unicode 碼,或者從相關的編碼查詢它是哪一個字符的編碼。C# 中字符的範圍擴大了,不僅包含了單字節字符,也可以包含雙字節字符,如中文字符等。而在字符和編碼之間的轉換,則仍延用了 C 語言的做法——強制轉換。
如下例:

        static void Main(string[] args)
        {
            char ch = 'a'; short ii = 65;
            Console.WriteLine("The ASCII code of " + ch + " is: " + (short)ch );
            Console.WriteLine("ASCII is " + ii.ToString() + ", the char is: " + (char)ii );

            char cn = '中'; short uc = 22478;
            Console.WriteLine("The Unicode of " + cn + " is: " + (short)cn);
            Console.WriteLine("Unicode is " + uc.ToString() + ", the char is: " + (char)uc);

            Console.ReadLine();
        }

運行結果:
The ASCII code of ‘a’ is: 97
ASCII is 65, the char is: A
The Unicode of ‘中’ is: 20013
Unicode is 22478, the char is: 城

從這個例子中,我們便能非常清楚的瞭解——通過強制轉換,可以得以字符的編碼,或者得到編碼表示的字符

3. 數值字符串和數值之間的轉換
將數值轉換成字符串非常簡單,因爲每一個類都有一個 void ToString() 方法。所有數值型的 void ToString() 方法都能將數據轉換爲數值字符串。如 123.ToSting() 就將得到字符串 “123”。

將數值型字符串轉換成數值 可以使用short, int, float 等數值類型的static Parse() 函數。這個函數就是用來將字符串轉換爲相應數值的。我們以一個 float 類型的轉換爲例: float f = float.Parse(“543.21”); 其結果 f 的值爲 543.21F。也可以使用Convert.ToInt16(string), Convert.ToInt32(string), Convert.ToSingle(string)等函數。
例子:

        static void Main(string[] args)
        {
            // 取一個double類型精確一位小數後的整數部分、小數部分和每個位的數字
            double val = 123.74;
            val = System.Math.Round(val, 1);

            string[] strs = val.ToString().Split('.');

            int gInteger = Convert.ToInt32(strs[0]);
            int gunitPlace = gInteger / 1 % 10;
            int gtenPlace = gInteger / 10 % 10;
            int ghundredPlace = gInteger / 100 % 10;
            int gthousandPlace = gInteger / 1000 % 10;

            Console.WriteLine("整數部分值爲:" + gInteger.ToString());
            Console.WriteLine("個位數值爲:" + gunitPlace.ToString());
            Console.WriteLine("十位數值爲:" + gtenPlace.ToString());
            Console.WriteLine("百位數值爲:" + ghundredPlace.ToString());
            Console.WriteLine("千位數值爲:" + gthousandPlace.ToString());

            int gdecimals = Convert.ToInt32(strs[1]);
            Console.WriteLine("小數部分值爲:" + gdecimals.ToString());

            Console.ReadLine();
        }

輸出結果爲:
整數部分值爲:123
個位數值爲:3
十位數值爲:2
百位數值爲:1
千位數值爲:0
小數部分值爲:7

4. 字符串和字符數組之間的轉換
字符串轉換爲字符數組:字符串類 System.String 提供了一個 void ToCharArray() 方法,該方法可以實現字符串到字符數組的轉換。
例子:

        static void Main(string[] args)
        {
            string str = "mytest";
            char[] chars = str.ToCharArray();

            Console.WriteLine("Length of str is " + str.Length);
            Console.WriteLine("Length of char array is " + chars.Length);
            Console.WriteLine("char[2] = " + chars[2]);

            Console.ReadLine();
        }

輸出:
Length of “mytest” is 6
Length of char array is 6
char[2] = t

字符數組轉換爲字符串: System.String 類有兩個構造函數是通過字符數組來構造的,即 String(char[]) 和 String[char[], int, int)。後者之所以多兩個參數,是因爲可以指定用字符數組中的哪一部分來構造字符串。而前者則是用字符數組的全部元素來構造字符串。
例子:

        static void Main(string[] args)
        {
            char[] tcs = {'t', 'e', 's', 't', ' ', 'm', 'e'};
            string tstr = new String(tcs);

            Console.WriteLine(tstr);
            Console.ReadLine();
        }

輸出:
test me

5. 字符串和字節數組之間的轉換
字符串轉換成字節數組: System.Text.Encoding。該類提供了 bye[] GetBytes(string) 方法將字符串轉換成字節數組。
在字符串轉換到字節數組的過程中,Encoding.Default 會將每個單字節字符,如半角英文,轉換成 1 個字節,而把每個雙字節字符,如漢字,轉換成 2 個字節。而 Encoding.Unicode 則會將它們都轉換成兩個字節。
例子:

        static void Main(string[] args)
        {
            string s = "C#語言";
            byte[] b1 = System.Text.Encoding.Default.GetBytes(s);
            byte[] b2 = System.Text.Encoding.Unicode.GetBytes(s);
            string t1 = "", t2 = "";
            foreach (byte b in b1)
            {
                t1 += b.ToString("") + " ";
            }
            foreach (byte b in b2)
            {
                t2 += b.ToString("") + " ";
            }

            Console.WriteLine("b1.Length = " + b1.Length);
            Console.WriteLine(t1);
            Console.WriteLine("b2.Length = " + b2.Length);
            Console.WriteLine(t2);

            Console.ReadLine();
        }

輸出:
b1.Length = 6
67 35 211 239 209 212
b2.Length = 8
67 0 35 0 237 139 0 138

字節數組轉換成字符串: 還提供了 string GetString(byte[]) 方法將字節數組轉換成字符串。
例子:

        static void Main(string[] args)
        {
            byte[] bs = { 97, 98, 99, 100, 101, 102 };
            string ss = System.Text.Encoding.ASCII.GetString(bs);
            Console.WriteLine("The string is: " + ss );

            Console.ReadLine();
        }

輸出:
The string is: abcdef

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章