Type conversion in C # .NET

zhaozj2021-02-16  86

C # coming out, there are some days. Recently, due to the needs of programming, some research on C # type conversion, the content involves C # pack box / unpacking / alias, numerical types of mutual conversion, character's ASCII code, and Unicode code, The conversion between the numerical strings and the value, the conversion between the string, and the character array / byte array, the conversion between the various numeric types, and the byte array, the hexadecimal output and some conversion of the date data Handling, share with you -

1. Pack, unpacking or alias

Many C # .NET books have an introduction Int-> int32 is a packing process, and it is the process of unboxing. The same is true for many other variables, such as Short <-> INT16, long <-> int64, etc. For general programmers, it is great to understand this process because these packing and unpacking actions can be done automatically, and do not need to write code for intervention. But we need to remember the relationship between these types, so we use "alias" to remember the relationship between them. C # is the language of the full-to-object, completely thorough than Java-oriented object - it puts the simple data type through the default packing action into a class. INT32, INT16, INT64, etc., the corresponding class name, and those we are familiar, simple and easy to book, such as int, short, long, etc., we can call it as an alias such as int32, int16, int64. So in addition to these three types, what kinds of "alias" are there? Commonly used some:

Bool -> System.Boolean (Boolean, its value is True or false)

Char -> system.char (character type, two bytes, indicating 1 Unicode character)

BYTE -> System.byte (byte, 1 byte, indicating 8 positive integers, range 0 ~ 255)

Sbyte -> system.sbyte (with symbolic byte, 1 byte, indicating 8-bit integer, range -128 ~ 127)

Ushort -> system.uint16 (no symbol short integer, 2 bytes, represent 16 positive integers, range 0 ~ 65, 535)

UINT -> System.uint32 (no symbol integer, 4 bytes, represent 32 positive integers, range 0 ~ 4, 294, 967, 295)

Ulong -> system.uint64 (no sign long integer, 8 bytes, indicating 64-bit positive integers, 20 to about 10)

Short -> System.Int16 (short integer, 2 bytes, 16-bit integer, range -32, 768 ~ 32, 767)

Int -> System.Int32 (integer, 4 bytes, representing 32-bit integers, range -2, 147, 483, 648 to 2, 147, 483, 647)

Long -> System.Int64 (long integer, 8 bytes, indicating 64-bit integers, scope - (19) (19) times to 10 in 19)

Float -> system.single (single precision floating point, 4 bytes)

Double -> system.double (double precision floating point, 8 bytes)

We can use the following code to make an experiment:

Private void testalias ()

{

// this.TextBox1 is a text box, the type is system.windows.forms.textbox // design has set its multiline property to TrueByte a = 1;

CHAR B = 'a';

Short c = 1;

INT D = 2;

Long E = 3;

UINT f = 4;

BOOL g = true;

this.TextBox1.text =

""

this.TextBox1.AppendText (

"BYTE ->" a.gettype (). Fullname

"/ n");

this.TextBox1.AppendText (

"char ->" b.gettype (). Fullname

"/ n");

this.TextBox1.AppendText (

"Short ->" C.gettype (). Fullname

"/ n");

this.TextBox1.AppendText (

"INT ->" D.gettype (). Fullname

"/ n");

this.TextBox1.AppendText (

"long ->" E.GETTYPE (). Fullname

"/ n");

this.TextBox1.AppendText (

"uint ->" f.gettype (). fullname

"/ n");

this.TextBox1.AppendText (

"BOOL ->" g.gettype (). FullName

"/ n");

}

Create a button in the form and call the Testalias () function in its click event, we will see that the results of the operation are as follows:

Byte -> System.byte

Char -> system.char

Short -> System.Int16

Int-> system.int32

Long -> System.Int64

Uint -> system.uint32

Bool -> System.Boolean

This is enough to illustrate the corresponding classes of each other!

2. Mutual conversion between numerical types

The numerical types mentioned here include Byte, Short, Int, long, fload, double, etc., according to this order, various types of values ​​can be automatically converted later. For example, assign a SHORT type data to an INT type variable, and the short value is converted to an INT value and then assigns an INT type variable. Such examples:

Private void testbasic ()

{

BYTE A = 1;

Short b = a;

INT C = B;

Long D = C;

FLOAT E = D;

Double f = e;

this.TextBox1.text =

""

this.TextBox1.AppendText (

"BYTE A =" a.tostring ()

"/ n");

this.TextBox1.AppendText (

"short b =" b.toString () "/ n");

this.TextBox1.AppendText (

"INT C =" C.Tostring ()

"/ n");

this.TextBox1.AppendText (

"long d =" D.toString ()

"/ n");

this.TextBox1.AppendText (

"float e =" e.tostring ()

"/ n");

this.TextBox1.AppendText (

"double f =" f.toString ()

"/ n");

}

The translation passed smoothly, the operation results were values ​​for each variable. Of course, their types are still the system.byte type ... System.double. Now let's try, if the order of assignment is, what is the order? Add a statement in the TestBasic () function:

INT g = 1;

Short h = g;

this.TextBox1.AppendText (

"h =" h.toString ()

"/ n");

Result compilation error: g: / projects / Visual C # / convert / form1.cs (118): Unable to convert the type "int" implicit to "short" where Form1.cs 118 lines are Short H = G.

At this time, if we insist on the conversion, it should be used to convert, which is often mentioned in the C language, which is to use the "(Type Name) variable name" form in the form of mandatory conversion. As described above, the modification is as follows:

Short g = 1;

BYTE H = (byte) g;

// Force the value of the SHORT type G, then assign the variable h after the SHORT type.

this.TextBox1.AppendText (

"h =" h.toString ()

"/ n");

Compilation passed, the result of the operation output h = 1, the conversion is successful. However, if we use forced conversion, you have to consider a problem: SHORT type is -32768 ~ 23767, and the Byte type is 0 ~ 255, then if the size of the variable G exceeds the BYTE type What kind of situation will there be? Let's rewrite the code again, change the value to 265, and 255 big 10

SHORT G = 265;

// 265 = 255 10

BYTE H = (byte) g;

this.TextBox1.AppendText (

"h =" h.toString ()

"/ n");

There is no error in compilation, but the results are not h = 265, but h = 9. Therefore, when we are converting, it should be noted that the data converted cannot exceed the scope of the target type. This is not only reflected in the multi-byte data type (relative, as the short of the above example) is converted to a small byte type (relative, as the byte of the above), it is also reflected in the same number of symbol types and non-symbol types as the number of bytes. If you convert the 129 of Byte to Sbyte will overflow. The examples in this regard are different, and it will not be described in detail. 3. Character's ASCII code and Unicode code

Many times we need to get an English character ASCII code, or a Unicode code of a Chinese character character, or from the related encoding query which character is encoded. Many people, especially from the VB program to learn C #, will report why C # does not provide ready-made functions to do this - because there is ASC () function and chr () function in VB for this type Conversion. But if you have learned C, you will clearly, we only need to convert English character data into a suitable numeric data, you can get the corresponding ASCII code; Converse, if a suitable numerical data is forced to convert Character data can get the corresponding characters. The range of characters in C # expands, not only contains a single-byte character, but also contains double-byte characters, such as Chinese characters. The conversion between characters and encodings still extension of C language practices - forced conversion. Let's take a look at the example below

Private void testchar ()

{

CHAR CH = 'a';

Short II = 65;

this.TextBox1.text =

""

this.TextBox1.AppendText (

"The ascii code of / '" ch

"/ 'IS:" (Short) CH

"/ n");

this.TextBox1.AppendText (

"ASCII IS" II.TOString ()

", The char is:" (char) II

"/ n");

CHAR CN = '""

Short uc = 22478;

this.TextBox1.AppendText (

"The unicode of / '" CN

"/ 'IS:" (Short) CN

"/ n");

this.TextBox1.AppendText (

"Unicode is" uc.tostring ()

", the char is:" (char) uc

"/ n");

}

Its operation result is

The Ascii Code of 'A' IS: 97

ASCII IS 65, THE CHAR IS: A

The Unicode of '' IS: 20013

Unicode is 22478, The Char is: City

From this example, we can understand that the character's encoding can be encoded, or the encoded characters can be obtained by forced conversion. If you are not Short type encoding, please refer to Article 1 for conversion, you can get the coded value of the INT. 4. Conversion between numerical strings and values

First of all, we have to understand what is a numeric string. We know that in C #, the string is represented by a number of characters contained in a pair of double quotes, such as "123". "123" is relatively special, because the characters that make up the string are numbers, such a string is a numerical string. In our eyes, this is a string of characters, but the computer only thinks it is a string, not a number. Therefore, when we are at some point, when entering a value, we convert a string into a value; at other times, we need the opposite conversion. Converting numeric values ​​into a string very simple because each class has a void toString () method. All numeric Void toString () methods can convert data to a numerical string. Such as 123.TOSTING () will result in a string "123". So in turn, what should I do if the numeric string is converted into a value? Let's take a closer look, you will find a Static Parse () function. This function is used to convert a string into a corresponding value. We use a float type to convert as an example: float f = float.parse ("543.21"); its result f is 543.21F. Of course, other numerical types can also be converted using the same method, and the following examples can more clearly describe the method of conversion:

Private Void TeststringValue ()

{

Float f = 54.321F;

String str =

"123";

this.TextBox1.text =

""

this.TextBox1.AppendText (

"f =" f.toString ()

"/ n");

IF

INT.PARSE (STR) == 123)

{

this.TextBox1.AppendText (

"Str Convert to int successfully.");

}

Else {

this.TextBox1.AppendText (

"Str Convert to int failed.");

}

}

operation result:

f = 54.321

Str Convert to int surpassfully.

5. Conversion between strings and characters arrays

String class system.string provides a void tocharaRray () method that enables strings to transition to character arrays. Such examples:

Private void teststringchars ()

{

String str =

"mytest";

Char [] chars = str.tochararray ();

this.TextBox1.text =

""

this.TextBox1.AppendText (

"Length of /" MyTest / "IS" Str.length

"/ n"); this.TextBox1.AppendText (

"Length of char Array is" Chars.length

"/ n");

this.TextBox1.AppendText (

"char [2] =" Chars [2]

"/ n");

In the case, the results are tested in the length of the character array of conversion to the conversion, and the results are as follows:

Length of "Mytest" IS 6

Length of char Array IS 6

Char [2] = T

It can be seen that the result is completely correct, this shows that the conversion is successful. So in turn, how do you want to convert the character array into a string? We can use the constructor of the System.String class to solve this problem. The System.String class has two constructor constructed by a character number, namely string (char []) and string [char [], int, int). The latter is more than two parameters because it can specify which part of the character array can be constructed. The former is a string with all the elements of the character array. We used to take the following statement as an example. In the teststringchars () function, enter the following statement:

Char [] tcs = {'t', 'e', ​​'s',' t ',', 'm', 'e'};

String TSTR =

New String (TCS);

this.TextBox1.AppendText (

"TSTR = /" TSTR

"/" / n ");

Enter TSTR = "Test Me", the test instruction conversion is successful. In fact, we often need to convert a string into a character array just to get a character in the string. If it is just for this purpose, it can not be able to convert the Master's move, we only need to use System.String [] operator to achieve the purpose. Please see the case, then add the following name in the TestStringChars () function:

CHAR CH = TSTR [3];

this.TextBox1.AppendText (

"/" " TSTR

"/" [3] = " ch.tostring ());

The correct output is "Test Me" [3] = T, tested, and the output is correct.

6. Conversion between strings and byte arrays

I am afraid you will be disappointed if you want to find the transition between the string and the byte array from the System.String class. In order to make such a conversion, we have to take another class: system.text.encoding. This class provides a BYE [] GetTes (String) method to convert a string into byte arrays, and provide string getString (Byte []) method converts the byte array into a string. System.Text.Encoding is similar to that there is no useful constructor, but we can find a few default encoding, eNCoding.default (coding of the current ANSI code page of the system), encoding.ascii (get 7 ASCII character set Encoding), encoding.Unicode (get encoding using the Little-Endian byte order), encoding.utf7 (getting encoded UTF-7 format), encoding.utf8 (getting UTF-8 format), etc. Here is the difference between Encoding.default and Encoding.Unicode for conversion. In the process of string to the byte array, Encoding.default will convert each single-byte character, such as half-width, and convert each double-byte character, such as Chinese characters into 2. One byte. Encoding. Enicode will convert them into two bytes. We can learn about the transformation by simple understanding of the way, and using Encoding.default and Encodeing.unicode: private void teststringBytes ()

{

String s =

"C # language";

Byte [] b1 = system.text.Encoding.default.getbytes (s);

BYTE [] B2 = system.text.encoding.unicode.getbytes (s);

String T1 =

"", t2 =

""

FOREACH

BYTE B

IN B1) {T1 = B.toString (

"")

"}

FOREACH

BYTE B

IN B2) {T2 = B.toString (

"")

"}

this.TextBox1.text =

""

this.TextBox1.AppendText (

"B1.LENGTH =" b1.length

"/ n");

this.TextBox1.AppendText (T1

"/ n");

this.TextBox1.AppendText (

"b2.length =" b2.length

"/ n");

THIS.TEXTBOX1.APpendText (T2

"/ n");

The results of the operation are as follows, not to say detailed, I believe everyone has already understood.

B1.LENGTH = 6

67 35 211 239 209 212

B2.LENGTH = 8

67 0 35 0 237 139 0 138

Convert byte arrays into strings, using the String getString (Byte []) or string getString (Byte [], int, int) method using the Encoding class, and what ENCODING is determined by the encoding. Add the following statement in the teststringbytes () function: byte [] BS = {97, 98, 99, 100, 101, 102};

String ss = system.text.Encoding.ascii.getstring (BS);

this.TextBox1.AppendText (

"THE STRING IS:" SS

"/ n");

The result is: The string is: abcdef

7. Conversion between various numerical types and byte arrays

In Article 1 we can find out how many bytes of spaces need to be used to save data. When a certain type of data is converted into byte array, it is necessary to be a corresponding size byte array; similarly, you need to convert byte arrays into numeric types, and this byte array is required to be greater than the corresponding numerical type. Section number. The protagonist of such conversion is now introduced: System.bitconverter. This class provides a BYTE [] getBytes (...) method to convert various numeric types into byte arrays, and also provides toint32, toint16, toint64, touint32, tositle, toboolean, etc. to convert byte arrays into corresponding values. Types of.

Since such transitions are usually only used when needed to make a thinner encoding / decoding operation, it will not be described in detail here, and only the System.bitConverter class is introduced to everyone.

8. Convert to hex

Any data is stored inside the computer, so that the amount of binding and data is not related to the data of the data is related to the input and output. So, for the credit conversion, we only care about the results in the string. The TSTRING () method can be converted into a string in paragraph 4, but in the string, the result is displayed in decimal. Now we bring it to add some parameters, you can convert it into hexadecimal - use the toString (String) method. Here you need a string type parameter, which is the format specifier. The hexadecimal format specifier is "X" or "X", the difference between the two format specifiers is mainly in the AF six numbers: "x" represents AF using lowercase letters, and "X" indicates AF Use a large letter letter. Such examples:

Private void testhex ()

{

INT A = 188;

this.TextBox1.text =

""

this.TextBox1.AppendText (

"a (10) =" a.tostring ()

"/ n");

this.TextBox1.AppendText (

"a (16) =" a.tostring (

"x")

"/ n");

this.TextBox1.AppendText (

"a (16) =" a.tostring (

"X")

"/ n");

The results of the operation are as follows:

a (10) = 188

A (16) = BC

A (16) = BC

At this time, we may have another demand, that is, in order to display the result, we need to control the length of hexadecimal representation, if the length is not enough, use the leader 0 to fill. To solve this problem, we only need to write a number that represents the length after the format specifier "x" or "x". For example, to limit the length of 4 characters, it can be written as "x4". Add a sentence in the above example: this.TextBox1.AppendText

"a (16) =" a.tostring (

"X4")

"/ n");

The result will output a (16) = 00bc. Now, we also have to say how to convert a string that represents a hexadecimal number of strings into integers. This conversion also needs to use the part () method. Here, I need Parse (String, System.globalization.NumberStyles) method. The first parameter is a string representing a hexadecimal number, such as "AB", "20" (indicating a decimal 32). The second parameter system.globalization.NumberStyles is an enumeration type that means that the hexadecimal enumeration value is HexNumber. Therefore, if we want to convert "ab" into integers, it should be written: int b = int.parse ("ab", system.globalization.numberStyles.HexNumber), the final result is 171.

9. Conversion between date-type data and long integer data

Why convert date-type data to long integer data? There are many reasons, but I personally often use it for date storage of the database. Since various databases are different from date-type definitions and processing, various languages ​​define the definition of date data is different, because I would rather convert the date-type data conversion to the database. Although the string can also be saved, the use of strings will also involve many issues, such as regions and other issues, and it needs to be more space than saving long integer data. Date data, when participating in C #, it should also be converted to long integer data to operate. Its long integer value is a number that is time-separated by 100 nanoseconds since 12:00 on January 1, 001. This number is called Ticks (scale) in the DateTime in C #. The DateTime type has a long integer read-only attribute called Ticks, saves this value. In this way, it is very simple to get a long type from a DataTime type data, just read the Ticks value of the DataTime object, such as:

Long longdate = datetime.now.ticks;

The DateTime is also provided, a function of constructing DateTime type data from a long integer data: DateTime (long). Such as:

DateTime these =

New datetime (longdate);

But so for many VB6 programmers, it has given them a problem, because the date data in VB6 is expressed in Double type, converting it to long integer, only date, and there is no time . How to coordinate these two date types? System.DateTime provides two functions of Double Tooadate () and Static DateTime FromoAdate (Double) to solve this problem. The former outputs the current object according to the original Double value, which gets a system.datetime object from a Double value. For example: private void testdatetimelong ()

{

Double Doubledate = datetime.now.tooadate ();

DateTime hasDate = datetime.fromoadate;

this.TextBox1.text =

""

this.TextBox1.AppendText (

Double Value of Now: " Doubledate.toString ()

"/ n");

this.TextBox1.AppendText (

"DateTime from double value:" thedate.tostring ()

"/ n");

operation result:

Double Value ofown: 37494.661541713

Datetime from Double Value: 2002-8-26 15:52:37

10. Format Date Data

During programming, it is usually necessary to output the date data according to certain formats. Of course, the output result is definitely a string. To do this, we need to use the TOSTRING () method of the System.DateTime class and specify a format string. In the MSDN, the mode string has a very detailed description of the mode string in the SYSTEMATINFO class, so I only explain some of the commonly used formats. First, please see the following table:

One day of one day in the month does not have a one-digit date in the preamble zero DD month. One-digit date with a leader zero DDD week a day of abbreviation name defines the full name of the day in the DDDD Week in Abbreviated DDAYNAMES. DayNames Defining M Month Number One Month No Pre-Paginal Zero MM Month Digital One-Average The Month There is a leading zero MMM monthly abbreviation name Defines the full name of MMMM month in monthnames in the monthnames in the monthnames. If the year does not include a year less than 10, the year whose year does not contain the year does not include the year, if the year does not include the year less than 10, it is displayed with the front guide YYY YYY, including the fourth digit of the Era, including the four-digit year of the Era, H12 hours The hourly number of hours of the hour does not have a preamble zero HH12 hourly hour a bit number of hidden hourly hourly hours a bit number of hours without preamble zero HH24 hours a one-digit hour The number of a number of more than one digit number has no preamble zero mm minutes a number of minutes a number of leading zero s second one-digit seconds no preamble zero SS second one number of seconds number of seconds

In order to facilitate everyone's understanding, try the procedures below:

Private void testdatetiMetString ()

{

DateTime now = datetime.now;

String format;

this.TextBox1.text =

""

Format =

"YYYY-MM-DD HH: MM: SS"; this.textBox1.AppendText (Format

":" now.toString (Format)

"/ n");

Format =

"YY Years M Day D Day";

this.TextBox1.AppendText (Format

":" now.toString (Format)

"/ n");

This program will output results:

YYYY-MM-DD HH: mm: SS: 2002-08-26 17:03:04

YY Years M Day D Day: On the 8th, 26th, 2002

At this time, there is a problem, what should I do if I have a format character in the text information to be output? Such as

Format =

"Year: YYYY, MONTH: MM, DAY: DD";

this.TextBox1.AppendText (now.toString (Format)

"/ n");

Will output:

2EAR: 2002, 4on under 5: 08, 26A2: 26

This is not what I want, what should I do? There is a way--

Format =

"/" Year / ": YYYY, / 'MONTH /': MM, / 'DAY /': DD";

this.TextBox1.AppendText (now.toString (Format)

"/ n");

Look, this time the results are right:

Year: 2002, Month: 08, Day: 26

转载请注明原文地址:https://www.9cbs.com/read-13267.html

New Post(0)