Type conversions in C #

Source: Internet
Author: User
Tags foreach aliases arrays bool numeric value string format variable tostring
Convert C # It's been some days, recently, due to the need for programming, some research has been done on C # 's type conversion, which covers boxing/unboxing/aliases of C #, conversion between numeric types, ASCII and Unicode codes for characters, conversions between numeric strings and numeric values, strings and character arrays/ Conversion between byte arrays, conversions between various numeric types and byte arrays, hexadecimal output, and some conversion processing of date data, here to share with you

1. box, unboxing or alias

Many c#.net books have introduced the int-> Int32 is a boxing process, whereas the reverse is the process of unpacking the box. This is true of many other variable types, such as short <-> int16,long <-> Int64. For the average programmer, it is not necessary to understand this process, because these boxes and unboxing actions can be automatically completed, do not need to write code to intervene. But we need to remember the relationships between these types, so we use "aliases" to remember the relationships between them.
C # is a fully object-oriented language, and is more thorough than Java object-oriented-it encapsulates simple data types through default boxing actions into classes. Int32, Int16, Int64 and so on are the corresponding class names, and those familiar, simple and easy to remember names, such as int, short, long, and so on, we can call it the Int32, Int16, Int64 and other types of aliases.
What other classes have "aliases" Besides these three types? Commonly used are the following:

BOOL-> System.Boolean (Boolean, whose value is true or false)
Char-> System.Char (character type, occupies two bytes, representing 1 Unicode characters)
byte-> system.byte (byte type, 1 bytes, 8-bit positive integer, range 0 ~ 255)
SByte-> System.SByte (signed byte, accounting for 1 bytes, representing 8-bit integers, range-128 ~ 127)
ushort-> system.uint16 (unsigned short integer, accounting for 2 bytes, representing 16-bit positive integers, range 0 ~ 65,535)
UINT-> system.uint32 (unsigned integer, accounting for 4 bytes, representing 32-bit positive integers, range 0 ~ 4,294,967,295)
ULONG-> System.UInt64 (unsigned long integer, accounting for 8 bytes, representing 64-bit positive integers, range 0 ~ approximately 10 20 times)
Short-> system.int16 (shorter 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 (8 bytes, representing 64-bit integers, range approximately-(10 of 19) to 10 of 19)
Float-> system.single (single-precision floating-point type, up to 4 bytes)
Double-> system.double (double-precision floating-point type, up to 8 bytes)

We can do an experiment with the following code:

private void Testalias () {
This.textbox1 is a text box with a type of System.Windows.Forms.TextBox
The Multiline property 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->" + 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 new button in the form and call the Testalias () function in its Click event, and we'll see the results of the run 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 explain each alias corresponding Class!

2. Conversion between numeric types

The numeric types mentioned here include Byte, short, int, long, fload, double, etc., according to which the various types of values can be automatically converted backwards in sequence. For example, to assign a short type of data to a variable of type int, the short value is automatically converted to an int value and then assigned to an int variable. The following 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 result is that the values of each variable are 1; Of course, their type is System.Byte type ... System.Double type. Now let's try, what if the order of assignment turns out to be? Append the following statement to the Testbasic () function:

int g = 1;
Short h = g;
This.textBox1.AppendText ("h =" + h.tostring () + "\ n");

Results compile an error:
G:\Projects\Visual C#\convert\form1.cs (118): Unable to implicitly convert type ' int ' to ' short '
Where the 118 line of Form1.cs is the line of short h = g.

This time, if we insist on conversion, we should use coercion type conversion, which is often mentioned in C language, using statements in the form of "(type name) variable name" to cast data. The above example is amended as follows:

Short g = 1;
byte h = (byte) g; Cast the value of the short type G to the short type and then assign to the variable H
This.textBox1.AppendText ("h =" + h.tostring () + "\ n");

The compiler passed, the results of the operation output H = 1, the conversion succeeded.
However, if we use a cast, we have to consider another problem: the short type range is 32768 ~ 23767, and the byte range is 0 ~ 255, so what happens if the size of the variable g exceeds the byte range? We might as well rewrite the code again, change the value to 265, 10 more than 255.

Short g = 265; 265 = 255 + 10
byte h = (byte) g;
This.textBox1.AppendText ("h =" + h.tostring () + "\ n");

There is no error in compiling, but the result is not H = 265, but H = 9.
Therefore, when converting, we should be aware that the converted data cannot exceed the scope of the target type. This is not only reflected in multibyte data types (relative, as in the case of short in the example above, when converted to a less-byte type (relative, as in byte in the example above), it is also reflected between the same signed and unsigned types of byte numbers, such as converting byte 129 to sbyte overflow. This is a very similar example, and it is not explained in detail.

3. ASCII code and Unicode code for characters

A lot of times we need to get an ASCII code for an English character, or a Unicode code for a kanji, or to query the encoding of which character it is from the associated encoding. Many people, especially those who have switched from VB to learning C #, complain that there are no ready-made functions to do this in C # because there are ASC () functions and CHR () functions in VB for such conversions.
But if you've studied C, you'll know that we just need to force the English character data to be converted to the appropriate numeric data, and we can get the corresponding ASCII code, otherwise, if a suitable numeric data is coerced into character data, the corresponding character can be obtained.
The range of characters in C # is expanded to include not only single-byte characters, but also double-byte characters, such as Chinese characters. In the case of conversion between characters and encodings, the C-language approach is still in force-casting. Consider the following example

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");
}
The result of its operation is

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

From this example, we can understand very clearly--by casting, you can encode the characters, or get the characters that are encoded. If you do not need a short type of code, please refer to the 1th to convert, you can get int and other types of encoded values.

4. Conversion between numeric string and numeric value

First, we need to figure out what a numeric string is. We know that in C #, strings are represented by a pair of characters contained in double quotes, such as "123". and "123" is relatively special, because the character that makes up the string is a number, such a string, is a numeric string. In our eyes, this is a string of characters, but also a number, but the computer only thinks it is a string, not a number. So, at some point, we convert a string to a numeric value when we enter a value, and at other times we need the opposite conversion.
Converting a number to a string is simple because each class has a void ToString () method. All numeric type void ToString () methods can convert data to numeric strings. such as 123.ToSting () will get the string "123".
So what happens when you convert a numeric string to a numeric value? When we look closely, we find that numeric types such as short, int, float have a static Parse () function. This function is used to convert the string to the corresponding numeric value. We take the example of a float-type conversion: float f = float. Parse ("543.21"); The value of the result F is 543.21F. Of course, other numeric types can also be converted using the same method, and the following example can be used to illustrate the conversion method more clearly:

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.");
}
}
Run 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 that enables the conversion of strings to character arrays. The following 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");
}
example, the length of the character array to which the transformation was converted and one of its elements were tested, with the following results:

Length of "MyTest" is 6
Length of char array is 6
CHAR[2] = t

As you can see, the results are completely correct, which means the conversion was successful. So what about converting character arrays to strings, in turn?
We can use the constructor of the System.String class to solve this problem. The System.String class has two constructors that are constructed from a character array, i.e. String (char[]) and string[char[], int, int. The latter has two more arguments because you can specify which part of the character array to construct the string. The former, however, constructs the string with all the elements of the character array. Let's take the former as an example and enter the following statement in the Teststringchars () function:

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

Run result input tstr = "Test Me", the test description succeeded.
In fact, many times we need to convert a string into a character array just to get a character in that string. If it's just for this purpose, it doesn't have to be selectmen to do the conversion, we just need to use the System.String [] operator to achieve the goal. Take a look at the example below and add the following name to 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 string and byte array

If you also want to find a way to convert between a string and a byte array from the System.String class, I'm afraid you'll be disappointed. To make this transition, we have to draw on another class: System.Text.Encoding. This class provides a bye[] GetBytes (String) method to convert a string to a byte array and a string GetString (byte[]) method to convert a byte array to a string.
The System.Text.Encoding class seems to have no constructors available, but we can find a few default Encoding, that is, Encoding.default (get the encoding of the system's current ANSI code page), Encoding.ascii (get 7-bit ASCII Character set encoding), Encoding.unicode (Get encoding in Unicode format in Little-endian byte order), ENCODING.UTF7 (Get encoding in UTF-7 format), Encoding.UTF8 (get UTF-8 format of the code) and so on. The main point here is the difference between Encoding.default and encoding.unicode for conversion.
In the process of converting a string to a byte array, Encoding.default converts each single-byte character, such as Half-width English, to 1 bytes, and converts each double-byte character, such as Chinese characters, to 2 bytes. And Encoding.unicode converts them all to two bytes. We can use the following simple understanding of the conversion method, as well as the difference between 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, do not say detailed, I believe we have understood.

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) method of the Encoding class, and what Encoding or encoding is used to specify. Add the following statement as an instance 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 of the run is: the string is:abcdef

7. Conversions between various numeric types and byte arrays

In article 1th, we can find out how many bytes of space the various numeric types need to use to hold the data. When you convert a numeric type of data to a byte array, you get a byte array of the appropriate size, and you also need to convert the byte array to a numeric type, which is larger than the number of bytes in the corresponding numeric type.
Now introduce the protagonist of such conversions: System.bitconverter. This class provides the byte[] GetBytes (...) method converts various numeric types into byte arrays, and also provides ToInt32, ToInt16, ToInt64, ToUInt32, Tosignle, ToBoolean method to convert a byte array to the corresponding numeric type.

Since such conversions are usually only used when more subtle encoding/decoding operations are required, this is not described in detail, and the System.bitconverter class is introduced to everyone.

8. Convert to hexadecimal

Any data is stored in binary form within the computer, so the system is not related to the storage of the data, but to the input and output. So, for a binary conversion, we only care about the results in the string.
In the 4th above, the ToString () method can be used to convert a numeric value to a string, but in a string, the result is displayed in decimal. Now we're going to add some arguments to it and we can convert it to hexadecimal--using the ToString (string) method.
This requires a string parameter, which is the format specifier. The hexadecimal format specifier is "x" or "X", and the difference between the two format specifiers is mainly the a-f six digits: "X" represents a-f using lowercase letters, whereas "X" means that A-f uses large letters. The following example:

private void Testhex () {
int a = 188;
This.textBox1.Text = "";
This.textBox1.AppendText ("a () =" + a.tostring () + "\ n");
This.textBox1.AppendText ("a () =" + a.tostring ("x") + "\ n");
This.textBox1.AppendText ("a () =" + a.tostring ("X") + "\ n");
}
The results of the operation are as follows:

A (10) = 188
A (a) = BC
A (a) = BC

At this point, we may have another requirement, that is, in order to display the results neatly, we need to control the length of the hexadecimal representation, if the length is not enough, with a leading 0 fill. To solve this problem, we just need to write a number representing the length of the format specifier "x" or "X". For example, to limit the length of 4 characters, you can write "X4". In the example above, add a sentence:

This.textBox1.AppendText ("a () =" + a.tostring ("X4") + "\ n");

The result will be output a (= 00BC).
Now, let's talk about how to convert a string that represents a hexadecimal number to an integral type. This transformation also requires the help of the Parse () method. Here, I need the Parse (string, System.Globalization.NumberStyles) method. The first parameter is a string that represents a hexadecimal number, such as "AB", "20" (representing 32 decimal), and so on. The second parameter, System.Globalization.NumberStyles, is an enumeration type, which is used to indicate that the hexadecimal enumeration value is hexnumber. So if we want to convert "AB" to an integral type, we should write this: int b = Int. Parse ("AB", System.Globalization.NumberStyles.HexNumber), the resulting B value 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 for this, but personally, it is often used for the date store of the database. Since the definitions and processing of date types vary from one database to another, the definitions of date-type data are handled differently in various languages, because I prefer to convert the date-type data into a form and then save it to a database. Although you can also use strings to save, using strings can also involve many problems, such as zones, and it requires more space than saving long integer data.
Date-type data, in C # 's participation in the operation, it should also be converted to long integer data to calculate. Its long value is the number that is represented by a 100-nanosecond interval of time since 12:00 midnight, January 1, 01. This number is called Ticks (scale) in the DateTime of C #. The DateTime type has a long, read-only property named Ticks that holds the value. Thus, it is very easy to get a long value from a datatime type of data, just read out the Ticks value of the Datatime object, such as:

Long longdate = DateTime.Now.Ticks;

The DateTime constructor also provides a corresponding function to construct the datetime data from the Long Integer data: datetime (Long). Such as:

DateTime thedate = new DateTime (longdate);

But that's a problem for a lot of VB6 programmers, because the date-type data in VB6 is represented by a Double, which, when converted to a long integer, gets only the date, not the time. How do you reconcile both types of dates?
System.DateTime provides a double tooadate () and a static DateTime FromOADate (double) two functions to solve this problem. The former outputs the current object by the original double value, and the latter obtains a System.DateTime object from a double value. Examples are 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");
This.textBox1.AppendText ("DateTime from Double value:" + thedate.tostring () + "\ n");
}
Run Result:

Double Value of now:37494.661541713
DateTime from Double value:2002-8-26 15:52:37

10. Format date-typed data

In the process of programming, it is usually necessary to output date-type data in a certain format, of course, the output is definitely a string. To do this, we need to use the ToString () method of the System.DateTime class and specify a format string for it.
MSDN, the System.Globalization.DateTimeFormatInfo class overview contains a very detailed description of the pattern string, so here I only describe some of the commonly used formats, first of all, look at the following table:

The date of one day in D month does not have a leading zero
The date of one day of the DD month has a leading zero
The abbreviated name of a day in the DDD week is defined in Abbreviateddaynames
The full name of a day in the dddd week is defined in DayNames
The month of the number of M months does not have a leading zero
MM month Number one number of month has a leading zero
The abbreviated name of the MMM month is defined in AbbreviatedMonthNames
The full name of the MMMM month is defined in MonthNames
Years that do not contain eras if the year that does not contain the era is less than 10, then the year with no leading zeros is displayed
YY does not contain eras if the year that does not contain the era is less than 10, then the year with leading zeros is displayed
YYYY a four-digit year that includes eras
H 12 Hour number of hours without leading zeros
HH 12-hour hourly number of hours has a leading zero
H 24 hour number of hours without leading zeros
HH 24-hour hourly number of hours has a leading zero
The number of minutes in m minutes does not have a leading zero
MM minute number of minutes has a leading zero
The number of seconds in s seconds does not have a leading zero
The SS second one digit number of seconds has a leading zero

For the sake of understanding, try the following procedure:

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. ToString (format) + "\ n");
}
This program will output the results:

YYYY-MM-DD hh:mm:ss:2002-08-26 17:03:04
YY year M day D: 02 8th 26th

At this point, another problem arises, what if the text message to be exported contains formatting characters? Such as

Format = "year:yyyy, month:mm, day:dd";
This.textBox1.AppendText (now. ToString (format) + "\ n");

Will output:

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

This is not the result that I want, how to do? There is a way--

format = "\ Year\": yyyy, \ ' month\ ': MM, \ ' day\ ': DD ';
This.textBox1.AppendText (now. ToString (format) + "\ n");

Look, the results of this operation are right:

year:2002, month:08, day:26

As you can see, just use single or double quotes to enclose the text information.





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.