(This article was published on August 28, 2002) C # .NET type conversion (continued) Border madman ===================
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 through the following 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 = "" "" "" "" "") "";} 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 result is as follows, not detailed, I believe that everyone has already understood.
B1.LENGTH = 6 67 35 211 239 209 212 B2.LENGTH = 8 67 0 35 0 237 139 0 138
Convert byte arrays into strings, using the String getString (Byte []) or string getString (Byte [], int, int) method using the Encoding class, and what ENCODING is determined by the encoding. Add as an instance of the following statement in the teststringbytes () function:
BYTE [] BS = {97, 98, 99, 100, 101, 102}; string ss = system.text.Encoding.ascii.getstring (bs); this.textBox1.AppendText ("THE STRING IS:" SS "/ n");
The result is: The string is: abcdef
7. Conversion between various numerical types and byte arrays
In Article 1 we can find out how many bytes of spaces need to be used to save data. When a certain type of data is converted into byte array, it is necessary to be a corresponding size byte array; similarly, you need to convert byte arrays into numeric types, and this byte array is required to be greater than the corresponding numerical type. Section number. The protagonist of such conversion is now introduced: System.bitconverter. This class provides a BYTE [] getBytes (...) method to convert various numeric types into byte arrays, and also provides toint32, toint16, toint64, touint32, tositle, toboolean, etc. to convert byte arrays into corresponding values. Types of.
Since such transitions are usually only used when needed to make a thinner encoding / decoding operation, it will not be described in detail here, and only the System.bitConverter class is introduced to everyone. 8. Convert to hex
Any data is stored inside the computer, so that the amount of binding and data is not related to the data of the data is related to the input and output. So, for the credit conversion, we only care about the results in the string. The TSTRING () method can be converted into a string in paragraph 4, but in the string, the result is displayed in decimal. Now we bring it to add some parameters, you can convert it into hexadecimal - use the toString (String) method. Here you need a string type parameter, which is the format specifier. The hexadecimal format specifier is "X" or "X", the difference between the two format specifiers is mainly in the AF six numbers: "x" represents AF using lowercase letters, and "X" indicates AF Use a large letter letter. Such examples:
Private void testHex () {int a = 188; this.textBox1.text = ""; this.textbox1.appendtext ("a (10) =" a.tostring () "/ n"); this.TextBox1. AppendText ("A (16) =" a.tostring ("x") "/ n"); this.TextBox1.AppendText ("a (16) =" a.tostring ("x") "/ n ");
The results of the operation are as follows:
A (10) = 188 a (16) = BC A (16) = BC
At this time, we may have another demand, that is, in order to display the result, we need to control the length of hexadecimal representation, if the length is not enough, use the leader 0 to fill. To solve this problem, we only need to write a number that represents the length after the format specifier "x" or "x". For example, to limit the length of 4 characters, it can be written as "x4". Add a sentence in the above example:
THIS.TEXTBOX1.APpendText ("A (16) =" a.tostring ("x4") "/ n");
The result will output a (16) = 00bc. Now, we also have to say how to convert a string that represents a hexadecimal number of strings into integers. This conversion also needs to use the part () method. Here, I need Parse (String, System.globalization.NumberStyles) method. The first parameter is a string representing a hexadecimal number, such as "AB", "20" (indicating a decimal 32). The second parameter system.globalization.NumberStyles is an enumeration type that means that the hexadecimal enumeration value is HexNumber. Therefore, if we want to convert "ab" into integers, it should be written: int b = int.parse ("ab", system.globalization.numberStyles.HexNumber), the final result is 171.
9. Why is the conversion between date data and long integer data to 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"); this.TextBox1.AppendText ("DateTime from Double Value:" thedate.toString () "/ n");}
operation result:
Double Value ofown: 37494.661541713 datete 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 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 in the month. There is no preamble zero. One day in the DD month. One-digit date has a preamble 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 daysNames. M month numbers. There is no preamble zero one month. MM month figures. One month has a preamble zero. MMM's abbreviation name is defined in AbbreviatedMonthnames. The full name of the MMMM month is defined in MonthNames. Y does not include the year of the era. If the year does not include a year less than 10, the year does not have a leading zero. YY does not contain the year of the era. If the year does not include a year less than 10, the year with the leading zero is displayed. YYYY includes the four-digit year of the era. H 12 hours. One of the few hours does not have a preamble zero. HH 12 hours of hours. One-digit hour has a preamble zero. H 24 hour hours. One of the few hours does not have a preamble zero. HH 24 hours. One-digit hour has a preamble zero. M minutes. One bit of minutes has no preamble zero. MM minutes. One of the number of minutes has a preamble zero. S second. One-digit seconds no preamble zero. SS seconds. A number of seconds has 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 results:
YYYY-mm-dd hh: mm: ss: 2002-08-26 17:03:04 YY year M-day D days: 26, 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 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. What if the text information contains double quotes or single quotes? This problem, please read the readers!