C # .Net Type Conversion (reprint)

Reprinted from: http://www.ynws.gov.cn/wsrs/blog/blogview.asp?logID=99

REVIEW article is to explain to the C # type conversion that involve a C # packing / unpacking / alias conversion between numeric type, between the transition between the transition between ASCII characters and Unicode code, string and numeric values, character arrays and string / byte array, and various types of numerical byte arrays Some conversion process of conversion, hexadecimal number, and the date data type. 
 
 

1. packing, unpacking or alias

many books C # .NET have introduced int -> Int32 packing is a process, and vice versa is unpacking process. Many other types of variables, too, such as: short <-> Int16, long <-> Int64 like. For the average programmer, no need to understand this process, because boxing and unboxing of these actions can all be done automatically, do not need to write code to intervene. But we need to remember that the relationship between these types, so we use the "Alias" to the relationship between them and memory.

C # is a fully object-language, object-oriented than Java are also completely - it's the simple data types by default packing packaged in a class action. Int32, Int16, Int64 and so is the corresponding class name, and those we are familiar, easy to remember names, such as int, short, long, etc., we can call it a Int32, Int16, Int64 other types of aliases. Then in addition to these three types, what kind of "Alias" mean? Some commonly used are the following:

BOOL -> System.Boolean The (Boolean values, either true or to false)

char -> the System.Char (character occupies two bytes representing a Unicode character)

byte -> System.Byte (byte, 1-byte, 8 denotes a positive integer, the range of 255 ~ 0)

sbyte -> the System.SByte (signed byte, 1-byte, an 8-bit integer, ~ range 127 -128)

ushort -> the System.UInt16 (unsigned short, 2 bytes, 16 represents a positive integer, the range of 65,535 ~ 0)

uint -> System.UInt32 The (unsigned integer representing the word 4 section, 32 denotes a positive integer, the range 4,294,967,295 ~ 0)

ulong -> a System.UInt64 (unsigned long, 8 bytes, 64 represents a positive integer, the range of 0 to about 20 power 10)

Short -> the System.Int16 (short integer, 2 bytes, 16 bits of integer, the range of ~ 32,767 -32,768)

int -> System.Int32 the (integer, representing four bytes, 32-bit integers, a range 2,147,483,648 to 2,147,483,647)

long -> System.Int64 (long, 8 bytes, represented by 64-bit integers, a range of about - (19 10) 19 th to 10 th) of

a float -> System.Single (single-precision floating-point , 4 bytes)

double -> System.Double The (double-precision floating-point, 8 bytes)

, we can use the following generations Do an experiment:

Private void testalias () {
    // this.textBox1 是一个文本框,类型为 System.Windows.Forms.TextBox
    // 设计中已经将其 Multiline 属性设置为 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 () the FullName + "\ the n-.");
} create a new button to the form, and call the TestAlias in its click event () function, we will see the results as follows:

byte -> System.Byte

char -> System.Char

Short -> System.Int16

int -> System.Int32

Long -> System.Int64

uint -> System.UInt32 the

BOOL -> System.Boolean

this illustrates alias each corresponding class!

2. The conversion between numeric types

here include numeric type byte, short, int, long, fload, double , etc., can be automatically converted back sequentially according to the order to this, various types of values. For Example, a short to a type of data assigned to a variable of type int, short value is automatically converted to type int row, int and then assign variable. In the following example:

Private void TestBasic () {
    byte = A. 1; B = A Short; C int = B;
    Long D = C; E = D a float; Double F = E;
    this.textBox1.Text = "";
    this.textBox1.AppendText ( "byte = A" + a.ToString () + "\ n-");
    this.textBox1.AppendText ( "Short B =" b.ToString + () + "\ n-");
    the this. textBox1.AppendText ( "C = int" + c.ToString () + "\ n-");
    this.textBox1.AppendText ( "Long D =" d.ToString + () + "\ n-");
    this.textBox1. AppendText ( "E = a float" e.toString + () + "\ n-");
    this.textBox1.AppendText (f.ToString + () + "\ n-" "Double F =");
} translation passed, running result is the value of the variables are 1; course, they are a type or type ...... System.Byte System.Double the type. Now let's try, if the order of assignment, in turn, what will happen? () Function in the following statement is added TestBasic:

int. 1 = G;

Short G = H;

this.textBox1.AppendText ( "H =" h.ToString + () + "\ n-");





Wherein Form1.cs line 118, i.e., short h = g row.

This time, if we stick to be converted, you should use the cast, which is often mentioned in the C language, is to use "(type name) variable name" form of the statement to be cast on the data. Example above modified as follows:

short. 1 g =;

byte H = (byte) g; // the value of g type short cast to type and then to a variable short H

this.textBox1.AppendText ( "H =" H + .ToString () + "\ n" );

compiler, the operation result output h = 1, the conversion was successful.

However, if we use a cast, it may no longer considered a problem: short type range is from -32768 to 23767, while the byte type range is from 0 to 255, then, if the variable g size exceeds the byte type and range What happens then? We might again rewrite the code, the value to 265, more than 255 large 10

Short G = 265; // 265 + 10 = 255

byte H = (byte) G;

this.textBox1.AppendText ( "H =" H +. ToString () + "\ n" );

compiles without errors, the result is not running h = 265, but h = 9.

Therefore, when we doing a conversion, it should be noted that the converted data can not exceed the range of the target type. When not only in the multi-byte data types (relatively, short as in the example) into a small type byte (In contrast, as in the example of byte), but also in the same number of bytes between a symbol type and unsigned types , as will be converted to byte 129 sbyte will overflow. Similar examples in this regard, not described in detail.
3. ASCII code characters and Unicode code

many times we need to get the ASCII character of an English or a Chinese character Unicode code, or code-related queries from which it is a character encoding. Many people, especially the transfer order came from a VB program people learn C #, it will complain in C # Why did not provide ready-made function to do this thing - because there Asc () function and Chr () function in VB for such conversion.

But if you learned C, you will know, we only need to cast English character data into the appropriate numeric data, you can get the corresponding ASCII code; on the contrary, if an appropriate cast to numeric data character data, the corresponding character can be obtained.

C # range of characters expanded to include not only single-byte characters, it can also contain double-byte characters, such as Chinese characters and so on. In the transition between the character and the encoding, we can still continue to use the C language practice - cast. Take a look at the following example

Private void TestChar () {
    char CH = 'A'; Short II = 65;
    this.textBox1.Text = "";
    this.textBox1.AppendText ( "of The code of the ASCII \ '" + CH + "\ 'is:"
    this.textBox1.AppendText ( "the ASCII IS" ii.ToString + () + ", The char IS:" + (char) II + "\ n-");
    char = CN 'in'; Short UC = 22478;
    the this. textBox1.AppendText ( "of the Unicode of The \ '" + CN + "\' IS:" + (Short) CN + "\ n-");
    this.textBox1.AppendText ( "IS the Unicode" uc.ToString + () + " , the char iS: "+ (char) UC +" \ n-");
} its operating result

of the the ASCII code of 'a' is: 97

the ASCII iS 65, the char iS: a

of the the Unicode of 'in' is : 20013

Unicode iS 22478, at the char iS: City

from this example, we will be able to understand very clearly - by casting, it can be encoded characters, or the character encoding to obtain representation. If not, you need short type encoding, please refer to Section 1 conversion, to obtain other types of encoded values int.

Converting between strings and numerical values 4

First, we have to thoroughly understand what is the value of the string. We know that, in C #, a plurality of strings by a pair of characters in double quotes is expressed as "123." The "123" and relatively specific, because the composition of the characters are numeric string, this string is the string value. In our eyes, this is a string of characters that is also a number, but the computer but only that it is a string, not a number. We therefore at some point, such as the input value when converted into a string value; in other times, we need vice versa.

Converting the value into a string is very simple, because each class has a void ToString () method. All numeric void ToString () method can be converted into a numerical data string. The 123.ToSting () will obtain the string "123."

So, in turn, converts the numeric string to a numeric how should we do? We take a close look, you will find short, int, float and other numeric types have a static Parse () function. This function is used to convert a string corresponding value. We conversion to an example of a float: float f = float.Parse ( "543.21 "); f is a result 543.21F. Of course, other types of values may be used to convert the same method, the following method can be more clearly illustrate examples of conversion:

Private void TestStringValue () {
    a float F = 54.321F;
    String STR = "123";
    this.textBox1. = the Text "";
    this.textBox1.AppendText ( "F =" F +.
    IF (the int.Parse (STR) == 123) {
        this.textBox1.AppendText ( "STR Convert to int successfully.");
    } the else {
        this.textBox1.AppendText ( "STR Convert to int failed.");
    }
} run results:

F = 54.321

STR convert to successfully int.

converting between strings and character arrays 5.

string System.String class provides a void ToCharArray () method, which may be implemented to convert the character string array. In the following example:

Private void TestStringChars () {
    String STR = "mytest";
    char [] = str.ToCharArray chars ();
    this.textBox1.Text = "";
    this.textBox1.AppendText ( "the Length of \" mytest \ " IS "str.length + +" \ n-");
    this.textBox1.AppendText ("
    this.textBox1.AppendText ( "char [2] =" chars + [2] + "\ n-");
} Example to conversion to convert the character array and the length of one of its elements were tested with the following results:

the Length of "mytest" IS. 6

the Length of char. 6 Array IS

char [2] = T

can be seen, the result is completely correct, indicating a successful conversion. So, in turn, make a character array into a string how?

We can use the System.String class constructor to solve this problem. System.String class has two constructors are constructed by a character array, i.e. String (char []) and String [char [], int, int). The reason why the multi latter two parameters, which can be specified because the portion of the array of characters to construct a string. While the former is to use all the elements of an array of characters to construct a string. We the former as an example, () function in the following statement entered TestStringChars:

char [] = {TCS 'T', 'E', 'S', 'T', '', 'm', 'E'};

TSTR = new new String String (TCS);

this.textBox1.AppendText ( "TSTR = \" "+ TSTR +" \ "\ n-");

operation result of the input tstr = "test me", the test described successful conversion.

In fact, we need to convert the string into an array of characters many times just to get a character in the string. If only for this purpose, which need not be scaled up to the conversion, we only need to use the System.String [] operator can achieve their goals. Consider the following example, and then () function is added as follows TestStringChars language name:

char CH = TSTR [. 3];

this.textBox1.AppendText ( "\" "+ TSTR +" \ "[. 3] =" + CH. the ToString ());

correct output is "test me" [3] = t, tested, correct output.

6. The conversion between strings and byte arrays

if you want to find a way to convert between strings and an array of bytes from the System.String class, I'm afraid you will be disappointed. In order to perform this conversion, we had to use another class: System.Text.Encoding. This class provides a bye [] GetBytes (string) method to convert the string into a byte array, also provides a string GetString (byte []) method to convert a byte array into a string.

System.Text.Encoding class constructor does not seem available, but we can find several default Encoding, namely Encoding.Default (get current ANSI code page encoding systems), Encoding.ASCII (get 7-bit ASCII character set coding), Encoding.Unicode (Little-Endian obtain encoded using a byte order of the Unicode format), Encoding.UTF7 (acquired encoding format UTF-7), Encoding.UTF8 (acquired encoding format UTF-8) and the like. Here mainly to talk about the difference between Encoding.Default and Encoding.Unicode for conversion.

In the string into a byte array conversion process, Encoding.Default will each single-byte characters, such as half-width English is converted into a byte, and each of the double-byte characters, such as Chinese characters, converted into 2 bytes. And Encoding.Unicode they will be transformed into two bytes. We can simply look at the following conversion method, and the difference between the use of 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 = "";
    the foreach (B in byte B1) {
        b.ToString + = T1 ( "") + "";
    }
    the foreach (B byte 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 + "\ the n-");
    this.textBox1.AppendText (T2 + "\ the n-");
}
results are as follows, do not say detailed, I believe we already know.

=. 6 b1.Length

67 35 211 239 209 212 

b2.Length =. 8

67 0 35 0 0 237 139 138 

Converting the byte array into a string, using string GetString Encoding class (byte []) or string GetString (byte [], int , int) method, which is determined by the encoding Encoding specific use. In TestStringBytes () function, the following statement is added as an example:

byte [] BS = {97, 98, 99, 100, 101, 102};

String = System.Text.Encoding.ASCII.GetString SS (BS);

this.textBox1 .AppendText ( "the string is:" + ss + "\ n");

run results: the string is: abcdef

conversion between values of various types and byte array 7.

in section 1, we can found various numerical model space using the number of bytes required to store the data. Converting some type of data value into a byte array when the corresponding size must be obtained byte array; Similarly, the need to convert the value into a byte array type, need byte array is greater than the corresponding value type of word Section number. Now introduce such conversions protagonist: System.BitConverter. This class provides byte [] GetBytes (...) method to convert various numerical values into a byte array type, also provides ToInt32, ToInt16, ToInt64, ToUInt32, ToSignle, ToBoolean the like to convert to the corresponding byte array value Types of.

Since this type of conversion is usually just need to be more subtle coding / decoding will be used when operating, so here not described in detail, only the System.BitConverter like to introduce to you.

8. converted to hexadecimal

Any data inside the computer are saved in binary, so the band has nothing to do with the storage of data, only with the input and output. So, for binary conversion, we are only interested in the result string.

ToString mentioned in section 4 above () method converts the value into a string, but in the string, the result is displayed in decimal. Now we bring it to add some parameters, you can convert it to hexadecimal - using ToString (string) method. It should be a parameter of type string, which is the format specifier. Hexadecimal format specifier is "x" or "X", the use of two formats that differ primarily specifier AF six numbers: "x" represents the representative af lowercase letters, and "X" represents the AF use characters letters. In the following example:

Private void TestHex () {
    int A = 188;
    this.textBox1.Text = "";
    this.textBox1.AppendText ( "A (10) =" + a.ToString () + "\ n-");
    the this .textBox1.AppendText (+ a.ToString ( "X") + "\ n-" "(16) = A");
    this.textBox1.AppendText ( "A (16) =" + a.ToString ( "X-") + "\ n");








At this time, we might have another demand, that is neat to show results, we need to control the length of the hexadecimal representation, if the length is not enough, padded with leading zeros. To solve this problem, we just need to explain the format of the symbol "x" or "X" indicates the length of the numbers written on the line. For example, to limit the length of 4 characters, it can be written as "X4". On an additional embodiment:

this.textBox1.AppendText ( "A (16) =" + a.ToString ( "X4") + "\ n-");

the result output a (16) = 00BC.

Now, we have to talk about how a hexadecimal number string into an integer. This conversion requires the same by means of the Parse () method. Here, I need to Parse (string, System.Globalization.NumberStyles) method. The first parameter is a hexadecimal number string, such as "AB", "20" (decimal 32) and the like. The second parameter is an enumeration type System.Globalization.NumberStyles for enumeration hexadecimal value HexNumber. So if we want to "AB" is converted to an integer, you should write: int b = int.Parse ( "AB ", System.Globalization.NumberStyles.HexNumber), the resulting value of b is 171.

9.

Conversion between the date data type and long data Why should the date data type into a long integer data it? Many reasons, but for me personally, it is often used to date database is stored. Due to various databases for defining and manipulating date type is not the same, various definitions of language processing date data type is also different, because I prefer to date type data into an integer growing again saved to the database. Although you can use a string to keep them, but also use a string involves many issues, such as problem areas, etc. Also, it needs to save more than long data space.

Date data type, time of participation in C # operations, should also be converted to a long integer data operations. It's a long value since 0001 on January 1 at 12:00 of the period to 100 nanoseconds after the interval when the digital representation. This number is called Ticks (scale) in the DateTime in C #. DateTime type has a long integer read-only property named Ticks, it holds that value. Thus, data obtained from a type DataTime long value is very simple, and only need to read the value of Ticks DataTime object, such as:

long longDate = DateTime.Now.Ticks;

constructor DateTime also provided in the corresponding function data from a long data type configured DateTime: DateTime (long). Such as:

DateTime theDate = new new DateTime (longDate);

but that for many VB6 programmers, is to give them out of a problem, because the date data type in VB6 is based on the internal representation of a Double, converts it to a double integer after the type to get only the date, but do not have time. How to reconcile these two types of date it?

System.DateTime provides double ToOADate () and static DateTime FromOADate (double) two functions to solve this problem. The former target current value according to the original double output, which is a value obtained from a double System.DateTime object. For example as follows:

Private void TestDateTimeLong () {
    Double doubleDate DateTime.Now.ToOADate = ();
    TheDate = DateTime.FromOADate the DateTime (doubleDate);
    this.textBox1.Text = "";
    this.textBox1.AppendText ( "Double value of now:" doubleDate.ToString + () + "\ n-");
    this.textBox1.AppendText ( "Double value from the DateTime:" theDate.ToString + () + "\ n-");
} run results:

Double value of now: 37494.661541713

the DateTime value from Double: 2002-8-26 15:52:37

10. The formatted date data type

during programming, it is generally necessary to date data type according to a certain output format, of course, it must be output string. To this end, we need to use the ToString () method System.DateTime class, and assign the format string. In MSDN, System.Globalization.




 



 

 Day of the week abbreviated name
 defined in the AbbreviatedDayNames in
 
dddd
 full name of the day of the week
 is defined in DayNames in
 
M
 month number
 month digit without leading zeros
 
MM
 month number
 -digit months have a leading zero
 
MMM
 abbreviated month name
 is defined in AbbreviatedMonthNames the
 
MMMM
 full name of the month
 in MonthNames defined
 
y
 the year without the century
 year without century is less than 10, is not shown to have leading zeros year
 
yy
 year without the century
 year without century is less than 10, the year is displayed with a leading zero
 
yyyy
 comprises a four-digit year epoch
  
 
h
 hour 12 hour
 several hours will not have a leading zero
 
hh
 hour 12 hour
 number of hours will have a leading zero
 
H
 24 hour clock
 Hours a number without leading zeros
 
HH
 24 hour clock
 number zero hours will have a preamble
 
m
 min
 -digit minutes are no leading zeroes
 
mm
 min
 -digit minutes to have a leading zero
 
s
 seconds
 a the median number of seconds with no leading zero
 
ss
 second
 digit seconds have a leading zero
 

in order to facilitate the understanding, try the following procedure:

Private void TestDateTimeToString () {
    DateTime now = DateTime.Now;
    String format;
    the this = .textBox1.Text "";
    the format = "the mM-dd-YYYY HH: mm: SS";
    this.textBox1.AppendText (the format + ":" + now.ToString (the format) + "\ n-");
    the format = "yy Year d day M day";
    this.textBox1.AppendText (format + ":" + now. ToString(format) + "\n");
} This program will output:

yyyy-MM-dd HH: mm: SS: 2002-08-26 17:03:04

YY day of M d Date: 2002 8th 26

At this time, a problem has emerged, If the text information to be output contains formatting characters how to do? As

the format = "year: YYYY, month The: the MM, Day: dd";

this.textBox1.AppendText (now.ToString (the format) + "\ n-");

output:

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

it's not the result I wanted, how to do it? There are ways -

the format = "\" year \ ": YYYY, \ 'month The \': the MM, \ 'Day \': dd";

this.textBox1.AppendText (now.ToString (the format) + "\ n-") ;

see, the results of the operation:

year: 2002, month the: 08, Day: 26

can be seen, only need to use single or double quotes to enclose it like a text message.

Reproduced in: https: //www.cnblogs.com/llbofchina/archive/2006/11/03/549496.html

Guess you like

Origin blog.csdn.net/weixin_34008805/article/details/94206723