C-enumeration, bitwise operation

Source: Internet
Author: User
Tags bitwise operators domain list
In practice, the value of some variables is limited to a limited range. For example, there are only seven days in a week, 12 months in a year, and six courses per week in a class. It is obviously inappropriate to describe these values as integer, dense, or other types. Therefore, the C language provides a type called "enumeration. All possible values are listed in the definition of the "enumeration" type. The value of the variable described as this "enumeration" type cannot exceed the defined range. It should be noted that the enumeration type is a basic data type, rather than a construction type, because it cannot be broken down into any basic type.

Enumeration type definition and description of enumeration Variables

I. Enumeration definition the general form of Enumeration type definition is:
Enum enumeration name
{Enumerated value table };
All available values should be listed in the enumerated values table. These values are also called enumeration elements.
Example: Enum weekday
{Sun, Mou, Tue, wed, Thu, Fri, sat };
The enumerated name is weekday. There are 7 enumerated values, that is, seven days in a week. The value of a variable described as weekday can only be one day in seven days.

2. The description of enumerated variables is similar to the description of the structure and union. The enumerated variables can also be described in different ways, that is, the description is first defined and then the description is also defined or directly described. The variables A, B, and C are described as the preceding weekday. You can use either of the following methods:
Enum weekday
{
......
};
Enum weekday A, B, C; or: Enum weekday
{
......
} A, B, C; or: Enum
{
......
} A, B, C;

Assignment and use of enumerated type variables

The following rules apply to enumeration types:
1. The enumerated value is a constant, not a variable. You cannot assign values to a value in a program. For example, if you assign the following values to the elements that enumerate weekday: Sun = 5; MON = 2; Sun = mon; all of them are incorrect.

2. The enumeration element itself is defined by the system as a numerical value indicating the serial number. The order starting from 0 is defined as 0, 1, 2 .... For example, in weekday, Sun is 0, mon is 1 ,..., The SAT value is 6.
Main (){
Enum weekday
{Sun, Mon, Tue, wed, Thu, Fri, sat} A, B, C;
A = sun;
B = mon;
C = Tue;
Printf ("% d, % d, % d", A, B, C );
}
3. Only enumeration values can be assigned to enumeration variables. The element values cannot be directly assigned to enumeration variables. For example, a = sum; B = mon; is correct. A = 0; B = 1; is incorrect. If you want to assign a value to an enumerated variable, you must use a forced type conversion, for example, A = (Enum weekday) 2. The meaning is to assign an enumeration element with a sequential number of 2 to the enumerated variable, equivalent to a = Tue. It should also be noted that enumeration elements are neither character constants nor string constants. Do not add single or double quotation marks when using them.
Main (){
Enum body
{A, B, c, d} month [31], J;
Int I;
J =;
For (I = 1; I <= 30; I ++ ){
Month [I] = J;
J ++;
If (j> d) J =;
}
For (I = 1; I <= 30; I ++ ){
Switch (month [I])
{
Case A: printf ("% 2D % C/T", I, 'A'); break;
Case B: printf ("% 2D % C/T", I, 'B'); break;
Case C: printf ("% 2D % C/T", I, 'C'); break;
Case D: printf ("% 2D % C/T", I, 'D'); break;
Default: break;
}
}
Printf ("/N ");
}

Bitwise operation

All the operations described above are performed in bytes as the most basic bit. However, many system programs usually require bitwise operations or processing. The C language provides the bitwise operation function, which allows the C language to be used to write system programs like the assembly language.
I. bitwise operators the C language provides six bitwise operators:
& Bitwise AND
| By bit or
^ Bitwise OR
~ Invert
<Move left
> Right shift

1. bitwise and operation bitwise AND operator "&" are binary operators. Its function is the binary phase corresponding to the two numbers involved in the operation. The result bit is 1 only when the two binary numbers are 1. Otherwise, the result bit is 0. The number of involved operations is supplemented.
For example, 9 & 5 can be written as follows: 00001001 (Binary complement of 9) & 00000101 (Binary complement of 5) 00000001 (Binary complement of 1) Visible 9 & 5 = 1.

Bitwise AND operations are usually used to clear some bits or retain some bits. For example, if a clears the high eight bits of 0 and retains the low eight bits, it can be used as a & 255 operation (255 of the binary number is 0000000011111111 ).
Main (){
Int A = 9, B = 5, C;
C = A & B;
Printf ("A = % d/Nb = % d/NC = % d/N", A, B, C );
}

2. bitwise OR operator "|" is a binary operator. Its function is the binary phase or corresponding to the two numbers involved in the operation. If one of the two binary numbers is 1, The result bit is 1. The two numbers involved in the operation appear as a complement.
Example: 9 | 5 writable formula: 00001001 | 00000101
00001101 (decimal 13) Visible 9 | 5 = 13
Main (){
Int A = 9, B = 5, C;
C = A | B;
Printf ("A = % d/Nb = % d/NC = % d/N", A, B, C );
}

3. bitwise exclusive or operation bitwise exclusive OR operator "^" is a binary operator. This function is used to calculate whether the binary numbers corresponding to the binary numbers are different or not. When the binary numbers of the two numbers are different, the result is 1. The number of involved operations still appears as a complement Code. For example, 9 ^ 5 can be written as follows: 00001001 ^ 00000101 00001100 (12 in decimal format)
Main (){
Int A = 9;
A = a ^ 15;
Printf ("A = % d/N", );
}

4. Search for Inverse operators ~ It is a single object operator and has the right combination. This function is used to reverse the binary numbers involved in the operation by bit. Example ~ 9 is calculated as follows :~ (0000000000001001) Result: 1111111111110110

5. The left shift operator <is a binary operator. Its function shifts the binary numbers on the left of "<" to several places left, And the number on the right of "<" to the specified number of digits,
High Discard, low fill 0. For example, a <4 refers to moving each binary of a four places to the left. For example, if a = 00000011 (decimal 3), after four digits are left removed, the value is 00110000 (decimal 48 ). 6. the right shift operator ">" is a binary operator. Its function is to shift all the binary numbers on the left of ">" to several places right, and the right of ">" to the specified number of digits.
For example, if a = 15, A> 2, 000001111 is shifted to 00000011 (decimal 3 ). It should be noted that, for the number of signed characters, the symbol bit will be moved along with the right shift. When it is a positive number, the maximum bit is 0, while the negative number, the sign bit is 1, the maximum bit is 0 or fill 1 depends on the provisions of the compilation system. Turbo C and many systems require completing 1.
Main (){
Unsigned A, B;
Printf ("input a number :");
Scanf ("% d", & );
B = A> 5;
B = B & 15;
Printf ("A = % d/TB = % d/N", a, B );
}
Let's look at another example!
Main (){
Char A = 'A', B = 'B ';
Int P, c, d;
P =;
P = (P <8) | B;
D = P & 0xff;
C = (P & 0xff00)> 8;
Printf ("A = % d/Nb = % d/NC = % d/ND = % d/N", A, B, C, D );
}

Bit domain

When storing some information, it does not need to occupy a full byte, but only needs to occupy a few or one binary bit. For example, when storing a switch value, there are only two States: 0 and 1. Use one binary digit. To save storage space and simplify processing, the C language also provides a data structure called "bit domain" or "bit segment ". The so-called "bit field" refers to dividing the binary character in a byte into several different regions and showing the digits of each region. Each domain has a domain name, which allows operations by domain name in the program. In this way, several different objects can be represented by a byte binary field. 1. Definition of a bit field and description of a bit field variable the definition of a bit field is similar to that of a structure, in the form:
Struct bit domain structure name
{Bit domain list };
The format of the bit domain list is: type description Character Domain Name: Bit domain Length
For example:
Struct BS
{
Int A: 8;
Int B: 2;
Int C: 6;
};
The description of bitfield variables is the same as that of structure variables. You can first define and then describe, and define or directly describe these three methods. For example:
Struct BS
{
Int A: 8;
Int B: 2;
Int C: 6;
} Data;
It indicates that data is a BS variable, which occupies two bytes in total. Where a occupies 8 places, B occupies 2 places, and C occupies 6 places. The definitions of bit domains are described as follows:

1. A single-byte field must be stored in the same byte, and cannot span two bytes. If the remaining space of one byte is insufficient to store another domain, it should be stored from the next unit. You can also intentionally start a domain from the next unit. For example:
Struct BS
{
Unsigned A: 4
Unsigned: 0/* airspace */
Unsigned B: 4/* stored from the next unit */
Unsigned C: 4
}
In the definition of this bit field, a occupies 4 bits in the first byte, And the last 4 bits enter 0 to indicate that it is not used. B starts from the second byte and occupies 4 bits, and C occupies 4 bits.

2. Because the bit field cannot span two bytes, the length of the bit field cannot exceed the length of one byte, that is, it cannot exceed 8-bit binary.

3. A bit domain can be a non-bit domain name. In this case, it is only used for filling or adjusting the position. An anonymous domain cannot be used. For example:
Struct K
{
Int A: 1
INT: 2/* The two digits cannot be used */
Int B: 3
Int C: 2
};
From the above analysis, we can see that the bit field is essentially a structure type, but its members are allocated by binary.

2. The use of bit domains is the same as that of structure members. The form is generally: Bit domain variable name-bit domain name can be output in various formats.
Main (){
Struct BS
{
Unsigned A: 1;
Unsigned B: 3;
Unsigned C: 4;
} Bit, * pbit;
Bit. A = 1;
Bit. B = 7;
Bit. c = 15;
Printf ("% d, % d, % d/N", bit. A, bit. B, bit. C );
Pbit = & bit;
Pbit-> A = 0;
Pbit-> B & = 3;
Pbit-> C | = 1;
Printf ("% d, % d, % d/N", pbit-> A, pbit-> B, pbit-> C );
}
In the preceding example, the bit domain structure Bs is defined. The three bit domains are A, B, and C. This section describes the BS type variable bit and the BS type pointer variable pbit. This indicates that pointers can also be used for bit fields.
The program's Lines 9, 10, and 11 assign values to the three single-digit domains. (Note that the value assignment cannot exceed the permitted range of the bit field) The program outputs the content of the three fields in integer format in line 1. Row 3 sends the bit address of the bit field variable to the pointer variable pbit. Row 14th re-assigns a value to bit field A as a pointer and assigns it to 0. Row 15th uses the compound bitwise operator "& =", which is equivalent to 7 in the original value of pbit-> B = pbit-> B & 3-bit Domain B, the bitwise AND operation result of 3 is 3 (111 & 011 = 011, And the decimal value is 3 ). Similarly, the Code uses the compound bitwise operation "| =" in line 1, which is equivalent to pbit-> C = pbit-> C | 1 and the result is 15. The program output the values of the three fields in the pointer mode in Row 3.

Typedef

The C language not only provides a wide range of data types, but also allows you to define the type specifiers by yourself, that is, allow the user to take the "alias" for the data type ". Typedef can be used to complete this function. For example, if there are integer values a and B, the description is as follows: int AA and B, where Int Is the type specifier of the integer variable. The complete expression of Int Is integer,
To increase the readability of the program, you can use typedef to define the integer specifier as typedef int integer, which can be used to replace int as the type description of the integer variable. For example, integer A and B; it is equivalent to int A and B. It is very convenient to define arrays, pointers, structures, and Other types with typedef, it not only makes the program easy to write but also makes the meaning clearer, thus enhancing readability. For example:
Typedef char name [20]; indicates that name is of the character array type and the array length is 20.
Then, the variables such as name A1, A2, S1, S2 can be used to describe the variables. They are equivalent to Char A1 [20], A2 [20], S1 [20], s2 [20]
Another example:
Typedef struct Stu {char name [20];
Int age;
Char sex;
} Stu;
Define Stu to indicate the structure type of Stu, and then use Stu to describe the structure variables: Stu body1, body2;
The general format defined by typedef is: the new type name of the original type name of typedef, the original type name contains the definition part, the new type name is generally expressed in uppercase,
Easy to differentiate. In some cases, macro definitions can be used to replace typedef functions. However, macro definitions are pre-processed, while typedef is compiled, which is more flexible and convenient.

Summary of this Chapter

1. enumeration is a basic data type. The values of enumeration variables are limited. Enumeration elements are constants rather than variables.

2. Enumeration variables are usually assigned values by the value assignment statement instead of dynamic input. Although enumeration elements can be defined by the system or user, enumeration elements and integers are different in different types. Therefore, the printf statement cannot be used to output element values (sequential values can be output ).

3. bitwise operations are a special operation function of C language. They are computed in binary units. Bitwise operators include logical operations and shift operations. Bitwise operators can combine with value assignment operators to form a composite value assignment operator. For example, <=, and <=.

4. Bit operations can be used to complete some functions of the assembly language, such as bit placement, bit clearing, and shift. It can also compress and store data and perform parallel operations.

5. A bit field is also a structure type in nature, but its Members allocate memory in binary bits. Its definition, description, and usage are the same as those in the structure.

6. Bit domains provide a means to compress data in advanced languages, saving storage space and improving program efficiency.

7. The type definition typedef provides users with a means to customize the type specifiers, taking care of the user's habits of programming and using vocabulary, and increasing the readability of the program.

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.