Tell the type conversion in C #

xiaoxiao2021-04-01  264

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, 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 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" ;tiis.textBox1.Appendtext ("char -> " b.gettype (). Fullname " /N");THIS.TEXTBOX1.AppendText ("short -> " c.gettype ) .Fullname "/N"; hexTextBox1.appendtext ("int -> " d.gettype (). Fullname " /N" ";tis.TextBox1.appendtext("long ->" e. GetType (). Fullname "/N"" ;THIS.TEXTBOX1.APpendText ("uint -> " f.gettype (). Fullname " /N"); hexTextBox1.AppendText ("Buol ->" g.gettype (). FullName "/ n");} New button in the form and call this Testalias () function in its click event, we will see that the results are as follows: Byte -> System .Betechar -> 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"" should () "/ n"); this.TextBox1.AppendText ("" "/ n"); this.textbox1.appendte (" INT C = " C.TOString () " /N ";tis.textbox1.appendtext("long d =" D.toString () "/N"); hextbox1.appendtext("Float E = " E.TOString () " /n" ";tis.textbox1.appendtext(" Double f = " f.toString () " / n ");} Translation is passed, the result is the variable The value is 1; of course, their types are still SYSTEM.BYTE types ... System.double. Now let's try, if the order of assignment is, what is the order? Add the following 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"); the compilation does not have an error, but the result is 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" ); hertbox1.appendtext ("s " ii.to.to.toTRING () ", The char is: " (char) ii " / n "); char CN = 'Chinese; 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 results are

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 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 fix.");} } 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 "; he.textbox1.appendtext("length of char array is" chars.length "/n"" should- "ips.textbox1.appendtext("char[2] =" chars [ 2] "/ n");} example is tested by an array length of the conversion to the conversion to one element, 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 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.uitode.getbytes (s); string t1 = ", t2 ="; forward (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"); hextbox1.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" ;tis.TextBox1. AppendText ("A (16) =" a.tostring ("x") "/N"" ;tis.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 as follows: private void TestDateTimeLong () {double doubleDate = DateTime.Now.ToOADate (); DateTime theDate = DateTime.FromOADate (doubleDate); this.textBox1.Text = ""; this.textBox1.AppendText ( "Double value of now : " Doubledate.toString () " /n" ";tis.textbox1.appendtext("Datetime from double value:" theDate.toTString () "/ n");} Run results:

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 is less than 10, the year does not include the year of the ethonization of the Era, if the year does not include the year less than 10, the year, the year, YYYY, including the lead, including the four-digit year of the era H 12 The hourly hourly number of hours had no preamble zero HH 12 hours a bit of hour a number of hidden zero HH 24 hours a bit number of hours without preamble zero HH 24 hours The number of times the number of bits There is no more than one number of minutes, no preamble zero mm minutes, one number of minutes, one number of leading zero s second one-digit number, no preamble zero SS second one number of seconds A preamble zero

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

Private void testdatetimetostring () {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 year M-day D day "; this.TextBox1.AppendText (Format ": " Now.toTRING (Format) " / n ") This program will output the result: YYYY-MM-DD HH: MM: SS: 2002-08-26 17: 03: 04YY Year M-day D days: 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.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.

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

New Post(0)