Type conversion in C #

Source: Internet
Author: User
Tags month name
Source: http://www.daima.com.cn/Info/28/Info29679/
Type conversion in C #
C # has been coming out for some days. Recently, due to programming needs, I have made some research on C # type conversion, the content involves C # Packing/unpacking/alias, mutual conversion between numeric types, ASCII and Unicode characters, conversion between numeric strings and numeric values, string and character array/byte conversion between arrays, conversion between various numeric types and byte arrays, hexadecimal output, and some Conversion Processing of date data, share with you here --
1. binning, unboxing, or Alias
2. Mutual conversion between numeric types
3. ASCII and Unicode characters
4. Conversion between a numeric string and a numeric value
5. Conversion between string and character array
6. Conversion between strings and byte Arrays
7. Conversion between various numeric types and byte Arrays
8. Convert to hexadecimal
9. Conversion between date data and long integer data
10. Format date data

1. binning, unboxing, or Alias

in many C #. net books, Int-> int32 is a packing process, and vice versa. The same applies to many other variable types, such as short <-> int16, long <-> int64. For general Program Members, you do not have to understand this process because these packing and unpacking actions can be completed automatically, you do not need to write Code for intervention. However, we need to remember the relationships between these types. Therefore, we use "aliases" to remember the relationships between them.
C # is a fully object-oriented language, which is more thorough than Java's object-oriented language-it encapsulates a simple data type into a class through the default packing action. Int32, int16, int64, and so on are the corresponding class names, and the familiar and easy-to-remember names, such as int, short, and long, we can call it an alias of the int32, int16, int64, and other types.
in addition to the three types, which classes have "aliases? The following are commonly used:

Bool-> system. boolean (boolean type, its value is true or false)
Char-> system. Char (Bytes type, occupies two bytes, indicating 1 UNICODE character)
Byte-> system. byte (byte, which occupies 1 byte, indicates an eight-digit positive integer, ranging from 0 ~ 255)
Sbyte-> system. sbyte (in byte notation, which occupies 1 byte, indicates an 8-digit integer, range:-128 ~ 127)
Ushort-> system. uint16 (unsigned short integer, which occupies 2 bytes and represents a 16-bit positive integer in the range of 0 ~ 65,535)
Uint-> system. uint32 (unsigned integer, 4 bytes, representing a 32-bit positive integer, range: 0 ~ 4,294,967,295)
Ulong-> system. uint64 (unsigned long integer, which occupies 8 bytes, indicates a 64-bit positive integer in the range of 0 ~ About 10 to the power of 20)
Short-> system. int16 (short integer, which occupies 2 bytes, indicates a 16-bit integer, range:-32,768 ~ 32,767)
INT-> system. int32 (integer, 4 bytes, representing a 32-bit integer, ranging from-2,147,483,648 to 2,147,483,647)
Long-> system. int64 (an integer of 8 bytes, representing a 64-bit integer. The value range is about-(19 of 10) to the 19th power of 10)
Float-> system. Single (single-precision floating point, 4 bytes)
Double-> system. Double (double-precision floating point type, 8 bytes)

We can use the following code for an experiment:

private void testalias () {
// This. textbox1 is a text box of the system type. windows. forms. textbox
// The multiline attribute has been set to true in the design.
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->" +. 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");
}< br> Create a button in the form and call the testalias () function in its click event, the running result is 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 indicate the classes corresponding to each alias!

2. Mutual conversion between numeric types

The value types mentioned here include byte, short, Int, long, fload, and double. According to the order, values of various types can be automatically converted backward. For example, if a short type data value is assigned to an int type variable, the short value is automatically converted to an int type value and then assigned to the int type variable. For example:

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 running result shows that the values of each variable are 1. Of course, their types are system. byte ...... System. Double type. Now let's try. What if we reverse the order of values? Append the following statement to 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): You cannot implicitly convert the type "int" to "short"
The first line of form1.cs is the row where short H = G is located.

At this time, if we insist on conversion, we should use forced type conversion, which is often mentioned in C language, that is, "(type name) variable name to forcibly convert data. The preceding example is modified as follows:

Short G = 1;
Byte H = (byte) g; // convert the value of the Short Type G to the short type and then assign it to the variable H.
This. textbox1.appendtext ("H =" + H. tostring () + "\ n ");

After compilation, H = 1 is output and the conversion is successful.
However, if we use forced conversion, we have to consider another problem: the short type range is-32768 ~ 23767, while the byte type ranges from 0 ~ 255. What will happen if the variable g size exceeds the byte range? Let's rewrite the code again and change the value to 265, which is 10 larger than 255.

Short G = 265; // 265 = 255 + 10
Byte H = (byte) g;
This. textbox1.appendtext ("H =" + H. tostring () + "\ n ");

There is no compilation error, but the running result is not h = 265, but h = 9.
Therefore, when performing conversion, we should note that the data to be converted cannot exceed the range of the target type. This is not only reflected in the conversion of the Multi-byte data type (relative, short in the above example) to the smaller byte type (relative, byte in the above example, it is also reflected in the conversion of byte 129 to sbyte between the same number of bytes of the signed type and the unsigned type. This example is similar and not detailed.

3. ASCII and Unicode characters

Most of the time, we need to get an ascii code of an English character, a unicode code of a Chinese character, or query the encoding of a character from the relevant encoding. Many people, especially those who learn C # From the VB program sequence, complain about why C # does not provide ready-made functions to do this-because there is ASC () in VB () functions and CHR () functions are used for this type of conversion.
However, if you have learned C, you will know that we only need to forcibly convert the English numeric data into appropriate numeric data to get the corresponding ASCII code. Otherwise, if you forcibly convert a suitable numeric data to numeric data, you can get the corresponding characters.
In C #, the character range is extended, including not only single-byte characters, but also double-byte characters, such as Chinese characters. The conversion between characters and encoding is still extended by the C language-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 = ''medium''; 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 running result is

The ASCII code of ''a' is: 97
ASCII is 65, the char is:
''' In the Unicode of '': 20013
Unicode is 22478, the char is: City

In this example, we can have a very clear understanding-through forced conversion, we can be able to encode or get the characters represented by encoding. If you do not need a short-type encoding, refer to the Code 1st for conversion to obtain the int and other types of encoding values.

4. Conversion between a numeric string and a numeric value

First, we need to understand what a numeric string is. We know that in C #, strings are represented by a pair of double quotation marks containing several characters, such as "123 ". And "123" is relatively special, because the characters that constitute the string are digits, such a string is a numerical string. In our eyes, this is a string of characters and a number, but the computer only considers it as a string, not a number. Therefore, in some cases, we convert a string to a value when entering a value. In other cases, we need to convert the string to a value on the contrary.
It is very easy to convert a value into a string because each class has a void tostring () method. All numeric void tostring () methods can convert data into numeric strings. For example, 123. tosting () will get the string "123 ".
What should we do if we convert a numeric string into a numeric value? We will find that there is a static parse () function for values such as short, Int, and float. This function is used to convert a string to a corresponding value. Let's take a float type conversion as an example: Float F = float. parse ("543.21"); the result F value is 543.21f. Of course, other numeric types can be converted using the same method. The following example gives a clearer description of the conversion method:

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 .");
}
}
Running result:

F = 54.321
STR convert to int successfully.

5. Conversion between string and character array

The string class system. String provides a void tochararray () method, which can be used to convert strings to character arrays. For example:

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 this example, the length of the converted character array and one of its elements are tested. 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, which indicates that the conversion is successful. In turn, what should we do if we want to convert character arrays into strings?
We can use the constructor of the system. string class to solve this problem. The system. string class has two constructor functions constructed through character arrays, namely, string (char []) and string [char [], Int, INT ). The latter has two more parameters because it can specify which part of the character array is used to construct the string. The former uses all elements of the character array to construct a string. For example, in the teststringchars () function, enter the following statement:

Char [] TCS = {'t'', ''e'', ''s '','''', ''m'', ''e ''};
String tstr = new string (TCS );
This. textbox1.appendtext ("tstr = \" "+ tstr +" \ "\ n ");

Enter tstr = "test me" in the running result. The test indicates that the conversion is successful.
In fact, many times we need to convert a string into a character array to obtain a character in the string. For this purpose alone, we do not need to perform conversion by using the [] Operator of system. String. Refer to the following example and add the following language name to the teststringchars () function:

Char CH = tstr [3];
This. textbox1.appendtext ("\" "+ tstr +" \ "[3] =" + CH. tostring ());

The correct output is "test me" [3] = T. After testing, the output is correct.

6. Conversion between strings and byte Arrays

if you want to find a method from the system. string class to convert the string and byte array, You may be disappointed. To perform this conversion, we have to use another class: system. Text. encoding. This class provides the Bye [] getbytes (string) method to convert a string to a byte array, and the string getstring (byte []) method to convert a byte array to a string.
system. text. the encoding class does not seem to have any constructors available, but we can find several default encoding, that is, encoding. default (get the system's current ANSI code page encoding), encoding. ASCII (get the encoding of the 7-bit ASCII character set), encoding. unicode (get the encoding in the unicode format in the little-Endian byte order), encoding. utf7 (get the encoding of the UTF-7 format), encoding. utf8 (get the encoding of the UTF-8 format) and so on. Here we mainly talk about the difference between encoding. Default and encoding. Unicode for conversion.
encoding. default converts each single-byte character, such as a half-width English character, into one byte, and converts each double-byte character, such as a Chinese character, into two bytes. Encoding. Unicode converts both of them into two bytes. The following describes the conversion methods and the differences between 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 running result is as follows. I believe you understand it.

B1.length = 6
67 35 211 239 209 212
B2.length = 8
67 0 35 0 237 139 0 138

Converts a byte array to a string using the string getstring (byte []) or string getstring (byte [], Int, INT) Methods of the encoding class, the encoding determines whether to use encoding. Add the following statement to the teststringbytes () function as an instance:

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 running result is: the string is: abcdef

7. Conversion between various numeric types and byte Arrays

In the first article, we can find the number of bytes required for various numeric types to store data. When you convert data of a numeric type to a byte array, the corresponding size of the byte array is obtained. Similarly, You need to convert the byte array to a numeric type, also, the byte array must be larger than the number of bytes of the corresponding value type.
The main character of this type of conversion is system. bitconverter. This class provides byte [] getbytes (...) methods To convert various numeric types into byte arrays. methods such as toint32, toint16, toint64, touint32, tosignle, and toboolean are also provided to convert byte arrays into corresponding numeric types.

This type of conversion is usually used only when more minor encoding/decoding operations are required, so we will not detail it here. We will only introduce the system. bitconverter class to you.

8. Convert to hexadecimal

Any data is saved in binary in the computer. Therefore, the binary system is irrelevant to the data storage and only related to the input and output. Therefore, for hexadecimal conversion, We only care about the results in the string.
The tostring () method can be used to convert a value into a string, but in the above 4th, the result is displayed in decimal. Now we can add some parameters to it to convert it to hexadecimal -- use the tostring (string) method.
Here we 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 lies in the A-F of six numbers: "X" indicates that a-f is represented by lowercase letters, while "X" indicates that the A-F is represented by uppercase letters. For example:

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 running result is as follows:

A (10) = 188
A (16) = BC
A (16) = BC

At this time, we may have another requirement, that is, to display the result neatly, we need to control the length of the hexadecimal representation. If the length is not enough, fill it with the leading 0. To solve this problem, we only need to write a number indicating the length after the format specifier "X" or "x. For example, to limit the length to 4 characters, you can write it as "X4 ". In the preceding example, add the following sentence:

This. textbox1.appendtext ("A (16) =" + A. tostring ("X4") + "\ n ");

The output result is a (16) = 00bc.
Now let's talk about how to convert a string that represents a hexadecimal number into an integer. This conversion also requires the parse () method. Here, I need the parse (string, system. Globalization. numberstyles) method. The first parameter is a hexadecimal string, such as "AB" and "20" (32 in decimal format. The second parameter system. Globalization. numberstyles is an enumeration type, which indicates that the hexadecimal enumeration value is hexnumber. Therefore, if we want to convert "AB" to an integer, we should write: int B = int. parse ("AB", system. globalization. numberstyles. hexnumber), and the final value of B is 171.

9. Conversion between date data and long integer data

Why do we need to convert data of the date type into long integer data? There are many reasons, but I personally often use it for the Date Storage of the database. Since various databases have different definitions and processes for the date type, the definitions of the date type data in different languages are also different, because, I would rather save the converted and grown integer data to the database. Although strings can also be saved, using strings also involves many problems, such as regions. In addition, it requires more space than saving long integer data.
Data of the date type should also be converted to long integer data During computation in C. Its long integer value is a number represented at an interval of January 1, 0001 milliseconds since midnight, January 1, 100. This number is called ticks (scale) in the datetime of C ). The datetime type has a read-only attribute named ticks, which stores the value. In this way, it is very easy to get the long value from a datatime data type. You only need to read the ticks value of the datatime object, for example:

Long longdate = datetime. Now. ticks;

The datetime constructor also provides the corresponding function for constructing datetime-type data from long integer data: datetime (long ). For example:

Datetime thedate = new datetime (longdate );

However, this is a difficult problem for many VB6 programmers, because the date data in VB6 is represented in double, after converting it to a long integer, only the date is obtained, and there is no time. How can we coordinate these two date types?
System. datetime provides the double tooadate () and static datetime fromoadate (double) functions to solve this problem. The former outputs the current object according to the original double value, and the latter obtains a system. datetime object from a double value. Example:

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 ");
This. textbox1.appendtext ("datetime from double value:" + thedate. tostring () + "\ n ");
}
Running result:

Double value of now: 37494.661541713
Datetime from double value: 2002-8-26 15:52:37

10. Format date data

During programming, the date data is usually output in a certain format. Of course, the output result must be a string. Therefore, we need to use the tostring () method of the system. datetime class and specify the format string for it.
In msdn, The system. Globalization. datetimeformatinfo class provides a very detailed description of the mode string. Therefore, here I only describe some common formats. First, see the following table:

The date of one digit in a day in month D has no leading zero
A single-digit date in a DD month has a leading zero
The abbreviated name of a day in DDD week is defined in abbreviateddaynames.
The full name of a day in the dddd week is defined in daynames.
The month with one digit in the M month has no leading zero.
MM indicates that the month with one digit has a leading zero.
The abbreviated Mmm month name is defined in abbreviatedmonthnames.
The full name of mmmm month is defined in monthnames.
Y does not include the year of the epoch. If the year of the epoch is not included, the year without the leading zero is displayed.
YY indicates the year that does not contain the epoch. If the year of the epoch is less than 10, the year with the leading zero is displayed.
Yyyy includes the four-digit year of the epoch.
The hour in the hour 12-hour format has no leading zero number of hours.
The hour in the HH 12-hour format has a leading zero number of hours.
The hour in the 24-hour format has no leading zero number of hours.
One-digit hour in HH 24-hour format has a leading zero
M-minute one-digit minutes without leading zero
The number of minutes in one-digit mm minute has a leading zero.
S second, one-digit number of seconds without leading zero
There is a leading zero in the number of seconds in a single digit in SS seconds.

To facilitate your understanding, try the following program:

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-m-d ";
This. textbox1.appendtext (format + ":" + now. tostring (Format) + "\ n ");
}
This program will output the results:

Yyyy-mm-dd hh: mm: SS: 2002-08-26 17:03:04
YY-m-D: 02-8-26

At this time, another problem occurs. What if the text to be output contains format characters? For example

Format = "Year: yyyy, month: Mm, Day: dd ";
This. textbox1.appendtext (now. tostring (Format) + "\ n ");

Output:

2ear: 2002, 4 on, 5: 08, 26a2: 26

This is not the result I want. What should I do? There is a way --

Format = "\" Year \ ": yyyy, \ ''month \'': Mm, \ ''day \ '': dd ";
This. textbox1.appendtext (now. tostring (Format) + "\ n ");

Check that the running result is correct:

Year: 2002, month: 08, Day: 26

you can see that you only need to enclose text information with single or double quotation marks.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.