C# 类型转换 example

2021-07-08 16:07

阅读:624

标签:abc   puts   little   doc   类型   返回   OLE   NPU   开头   

示例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

标签:abc   puts   little   doc   类型   返回   OLE   NPU   开头   

原文地址:https://www.cnblogs.com/brt3/p/9736473.html


评论


亲,登录后才可以留言!