Type conversion in C #

xiaoxiao2021-03-06  103

The type conversion C # out of C # comes out, there are some days, recently due to the need for programming, some research on the type of C #, which involves the C # pack box / unpack / alias, numerical types, Mutual conversion, Characters ASCII Code and Unicode code, the conversion between the character string and the character array / byte array, the conversion between various numeric types, and the number of byte arrays, the number of hexadecimal outputs and the date Some conversion processing of type data, sharing with you here -

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, represents 1 Unicode character) Byte -> System.byte (byte, 1 byte, indicating 8 positive integers, range 0 ~ 255) sbyte -> system.sbyte (with symbolic byte type, 1 byte, indicating 8-bit integer, range -128 ~ 127) Ushort -> system. UINT16 (unsigned short integer, 2 bytes, indicating 16 positive integers, range 0 ~ 65, 535) uint -> system.uint32 (no symbol integer, 4 bytes, representing 32-bit positive integers, range 0 ~ 4, 294, 967, 295) Ulong -> System.uint64 (no sign long, accounting for 8 bytes, indicating 64-bit positive integers, ranging from 0 to about 10) SHORT -> System.Int16 (short integer, 2 words Section, indicating 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, With 8-byte, representing 64-bit integers, scope - (10 19) (10) 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 True

BYTE 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.bytechar -> system.charshort -> System.int16int -> system.int32long -> System.int64uint -> System.uint32bool -> 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 ("whip 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; // Mandatory for the value of the SHORT type G and then assigns the variable hthis.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 10Byte 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 = 'in'; 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: 97ASCII IS 65, The Char IS: ATHE Unicode of '' IS: 20013Unicode 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 numeric types can also be converted using the same method, and the following examples can be more clearly described; 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.321str 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 6Length of char Array is 6char [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 (THIS); 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 conversion by following a 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 = 667 35 211 239 209 212 b2.length = 867 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 .Appendte ("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) = 188A (16) = BCA (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 has DateTime.Fromoadate (doubledate);

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.661541713datetime 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.toTString (Format) "/ n"); Format = "YY Years M S Japan";

THIS.TEXTBOX1.APpendText (Format ":" Now.toTRING (Format) "/ N");

}

This program will output results:

YYYY-mm-dd hh: mm: s: 2002-08-26 17: 03: 04yy year M-day D day: 8th, 8th, 26

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.toTString (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.toTString (Format) "/ N");

Look, this time the results are right:

Year: 2002, Month: 08, Day: 26

It can be seen that it only needs to use single quotes or double quotes to enclose text information. -------------------------------------------------- -------------------------------------------------- ----- [This article is transferred from the western e-network]

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

New Post(0)