TryParse
Normally, if you want to convert a string similar to 1024
or 3.14
to a value of the corresponding data type, you only need int.Parse
or double.Parse
. If the input is an array, there is no problem, just divide it, for example
string test = "5,2,0";
int i = 0;
foreach(var item in test.Split(','))
bs[i++] = int.Parse(item);
And there is no pressure to convert hexadecimal, just
int.Parse("AB", System.Globalization.NumberStyles.HexNumber);
In C#, Parse
it is a very unified function, such as int, uint, double
data types, etc., all provide parse
functions for converting strings into corresponding data types.
But parse
it is not safe. If the input parameters do not meet the requirements, an error will be reported and the program will crash. For example, converting abc
it to an integer is obviously impossible. Therefore, C#
a conversion scheme without error reporting is provided, that is TryParse
, its usage is as follows
int intOut;
while (true)
{
string? str = Console.ReadLine();
if (int.TryParse(str, out intOut))
Console.WriteLine($"您输入了数字{
str}");
else
Console.WriteLine("输入不合法");
}
The effect is
1234
您输入了数字1234
asdf
输入不合法
Convert
In practical applications, converting a hexadecimal string to a byte array is a very common requirement. If it is byte.Parse
relatively troublesome to use, a more advanced conversion function is needed at this time Convert
. The call is very simple, first come Demonstrate conversion of a single value
int intOut = Convert.ToByte("AB", 16);
16 means hexadecimal, Convert
a series of functions, supports 2, 8, 10 and 16.
Convert
It also supports conversion from other types to strings. Still taking hexadecimal conversion as an example, the output of the following code is 19.
string str = Convert.ToString(25, 16);
Console.WriteLine(str);
However, the above conversion between single values and strings does not actually show Convert
the power of this static class, and Convert
the most convenient function provided is actually the conversion between byte arrays and strings, for example
var bs = Convert.FromHexString("6400");
foreach (var item in bs)
Console.WriteLine(item);
Its return result is
100
0
Among them, 0x64
100 in base 10 0x00
is 0.
combat
In daily use, hexadecimal byte arrays are often written in 0xAA, 0xBB
this form, and through String.Format
functions, byte arrays can be output as strings in this format
string str = "";
byte[] bs = new byte[] {
1, 15, 100, 127 };
foreach (var b in bs)
str += $"0x{
b:X},"; // $字符串和Format函数语法十分相似
Console.WriteLine(str);
The output is
0x01,0x0F,0x64,0x7F,
If you want to restore it to a byte array, there are two options. One is to divide it into a string array and call it one by one byte.Parse
, but a better way is to directly remove 0x
the remaining ones ,
, and then callFromHexString
str = str.Replace("0x", "").Replace(",", "");
bs = Convert.FromHexString(str) ;
foreach (var b in bs)
Console.WriteLine(b);
The effect is as follows
1
15
100
127