Conversion between C# strings, numeric types, and byte arrays

Article directory

TryParse

Normally, if you want to convert a string similar to 1024or 3.14to a value of the corresponding data type, you only need int.Parseor 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#, Parseit is a very unified function, such as int, uint, doubledata types, etc., all provide parsefunctions for converting strings into corresponding data types.

But parseit 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 abcit 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.Parserelatively 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, Converta series of functions, supports 2, 8, 10 and 16.

ConvertIt 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 Convertthe power of this static class, and Convertthe 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, 0x64100 in base 10 0x00is 0.

combat

In daily use, hexadecimal byte arrays are often written in 0xAA, 0xBBthis form, and through String.Formatfunctions, 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 0xthe 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

Guess you like

Origin blog.csdn.net/m0_37816922/article/details/130868580