1. 程式人生 > >C# 類型轉換 example

C# 類型轉換 example

ons cal amp correct ESS absolut val cep pan

示例1:從網絡讀取字節之後,將字節轉換為內置數據類型

下表列出了 BitConverter 類中將字節(來自字節數組)轉換為其他內置類型的方法。

返回類型方法
bool ToBoolean(Byte[], Int32)
char ToChar(Byte[], Int32)
double ToDouble(Byte[], Int32)
short ToInt16(Byte[], Int32)
int ToInt32(Byte[], Int32)
long ToInt64(Byte[], Int32)
float ToSingle(Byte[], Int32)
ushort ToUInt16(Byte[], Int32)
uint ToUInt32(Byte[], Int32)
ulong ToUInt64(Byte[], Int32)

將字節數組轉換為整型:

byte[] bytes = { 0, 0, 0, 25 };

// If the system architecture is little-endian (that is, little end first),
// reverse the byte array.
if (BitConverter.IsLittleEndian) Array.Reverse(bytes); int i = BitConverter.ToInt32(bytes, 0); Console.WriteLine("int: {0}", i); // Output: int: 25

將整型轉換為字節數組:

byte[] bytes = BitConverter.GetBytes(201805978);
Console.WriteLine("byte array: " + BitConverter.ToString(bytes));
// Output: byte array: 9A-50-07-0C

示例2:字符串轉換為數字

可以使用 Convert 類中的方法或使用各種數值類型(int、long、float 等)中的 Parse()、TryParse() 方法將字符串轉換為數字。如果字符串的格式無效,則 Parse() 會引發異常,而 TryParse() 會返回 false。

Parse 和 TryParse 方法會忽略字符串開頭和末尾的空白符,但其他所有字符都必須是組成合適數值類型(int、long、ulong、float、decimal 等)的字符。 如果組成數字的字符中有任何空白符,都會導致錯誤出現。

實際上,Convert.ToUInt32 方法在內部使用 Parse。

try {
    int m = Int32.Parse("abc");
}
catch (FormatException e) {
    Console.WriteLine(e.Message);
}
// Output: Input string was not in a correct format.
-----------------------------------------------------------------------------
string inputString = "abc";
bool parsed = int.TryParse(inputString, out int numValue);

if (!parsed)
    Console.WriteLine("Int32.TryParse could not parse ‘{0}‘ to an int.\n", inputString);
else
    Console.WriteLine($"Convert the string to num: {numValue}");

// Output: Int32.TryParse could not parse ‘abc‘ to an int.

下表列出了 Convert 類中可使用的一些方法,例如: numVal = Convert.ToInt32(input);

數值類型方法
decimal ToDecimal(String)
float ToSingle(String)
double ToDouble(String)
short ToInt16(String)
int ToInt32(String)
long ToInt64(String)
ushort ToUInt16(String)
uint ToUInt32(String)
ulong ToUInt64(String)

示例3:在十六進制字符串與數值類型之間轉換

獲取字符串中每個字符的十六進制值

string input = "Hello World!";
char[] values = input.ToCharArray();
foreach (char letter in values)
{
    // Get the integral value of the character.
    int value = Convert.ToInt32(letter);
    // Convert the decimal value to a hexadecimal value in string form.
    string hexOutput = String.Format("{0:X}", value);
    Console.WriteLine("Hexadecimal value of {0} is {1}", letter, hexOutput);
}
// Output:
//    Hexadecimal value of H is 48 ...

獲取與十六進制字符串中的每個值對應的 char

string hexValues = "48 65 6C 6C 6F 20 57 6F 72 6C 64 21";
string[] hexValuesSplit = hexValues.Split( );
foreach (string hex in hexValuesSplit)
{
    // Convert the number expressed in base-16 to an integer.
    int value = Convert.ToInt32(hex, 16);
    // Get the character corresponding to the integral value.
    string stringValue = Char.ConvertFromUtf32(value);
    char charValue = (char)value;
    Console.WriteLine("hexadecimal value = {0}, int value = {1}, char value = {2} or {3}",
                        hex, value, stringValue, charValue);
}
// Output:
//    hexadecimal value = 48, int value = 72, char value = H or H ...

將十六進制 string 轉換為 int

string hexString = "8E2";
int num = Int32.Parse(hexString, System.Globalization.NumberStyles.HexNumber);
Console.WriteLine(num);
//Output: 2274

將十六進制 string 轉換為 float

string hexString = "43480170";
uint num = uint.Parse(hexString, System.Globalization.NumberStyles.AllowHexSpecifier);

byte[] floatVals = BitConverter.GetBytes(num);
float f = BitConverter.ToSingle(floatVals, 0);
Console.WriteLine("float convert = {0}", f);
// Output: 200.0056

將字節數組轉換為十六進制 string

byte[] vals = { 0x01, 0xAA, 0xB1, 0xDC, 0x10, 0xDD };

string str = BitConverter.ToString(vals);
Console.WriteLine(str);

str = BitConverter.ToString(vals).Replace("-", "");
Console.WriteLine(str);

/*Output:
  01-AA-B1-DC-10-DD
  01AAB1DC10DD
 */

C# 類型轉換 example