C# Convert類解決問題方法
你有一個包含二進(jìn)制數(shù)、八進(jìn)制數(shù)、十進(jìn)制數(shù)或十六進(jìn)制數(shù)的字符串。你需要把它轉(zhuǎn)換為等價的數(shù)值并用十進(jìn)制表示出來。
C# Convert類解決方法:
要把一個其他進(jìn)制的數(shù)轉(zhuǎn)換為十進(jìn)制數(shù),只要用C# Convert類的被重載的靜態(tài)方法Convert.ToInt32即可:
- string base2 = "11";
 - string base8 = "17";
 - string base10 = "110";
 - string base16 = "11FF";
 - Console.WriteLine("Convert.ToInt32(base2, 2) = " +
 - Convert.ToInt32(base2, 2));
 - Console.WriteLine("Convert.ToInt32(base8, 8) = " +
 - Convert.ToInt32(base8, 8));
 - Console.WriteLine("Convert.ToInt32(base10, 10) = " +
 - Convert.ToInt32(base10, 10));
 - Console.WriteLine("Convert.ToInt32(base16, 16) = " +
 - Convert.ToInt32(base16, 16));
 
代碼產(chǎn)生這樣的輸出結(jié)果:
- Convert.ToInt32(base2, 2) = 3
 - Convert.ToInt32(base8, 8) = 15
 - Convert.ToInt32(base10, 10) = 110
 - Convert.ToInt32(base16, 16) = 4607
 
討論:
靜態(tài)方法Convert.ToInt32有兩個參數(shù),一個包含數(shù)字的字符串和一個表示該數(shù)字進(jìn)制的整數(shù)。接著這個函數(shù)就會把這個數(shù)字字符串轉(zhuǎn)換為十進(jìn)制整數(shù)了。
C# Convert類的其他靜態(tài)函數(shù),比如ToByte,ToInt64和ToInt16,也有類似的重載,即接受一個字符串類型的數(shù)字和一個表示該數(shù)字進(jìn)制的整數(shù)。不過這些方法只能轉(zhuǎn)換那些二進(jìn)制、八進(jìn)制、十進(jìn)制或十六進(jìn)制的數(shù)。它們只能把這些數(shù)轉(zhuǎn)換為十進(jìn)制的數(shù)。但是,任何類型的數(shù)值的ToString都可以轉(zhuǎn)換成 string類型。
【編輯推薦】















 
 
 


 
 
 
 