Bit operations in C #, non-logical ~, Logical and &, logical or |, logical XOR or ^, logical left shift

Source: Internet
Author: User
Tags domain list
Turn... Bit operations in C #, non-logical ~, Logical and &, logical or |, logical XOR or ^, logical left shift <, logical right shift>

In C #, we will use in-place operations. For example, to determine whether a number is the power of 2, how to determine whether a number is the power of 2 must be implemented using bitwise operations, use and operation, and shift left.
The specific functions can be as follows,
Public boolen getifright (INT num)

If (Num <= 1)
Return true;
Return (Num & (num-1) = 0 )? True; false;

In this way, we can determine whether the number is the N power of 2. If yes, true will be returned.



1. bitwise AND operator (&)
1. Operation Rules
For the two data involved in the operation, the "and" operation is performed by binary. If the two corresponding binary values are 1, The result value of this bit is 1; otherwise, it is 0, that is:
0 & 0 = 0 0 & 1 = 0, 1 & 0 = 0, 1 & 1 = 1.
2. Purpose
(1) resetting
Calculation object: the first digit in the original number, and the corresponding digit in the new number is 0.
(2) locate certain indicators in a number.
To take the low (high) byte of an integer a (two bytes), you only need to bitwise the 377 (177400) of A and 8 bytes.
(3) retain a certain digit Of a certain number.
Perform an & operation with a number. This number is 1 in this bit.
3. For example, 9 & 5 can be written as follows: 00001001 (Binary complement of 9) & 00000101 (Binary complement of 5) 00000001 (Binary complement of 1) 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 (|)
1. Operation Rules
For the two data involved in the operation, the "or" operation is performed by binary. If both of the two data are 0, the result value of this bit is 0; otherwise, it is 1, that is:
0 | 0 = | 1 = | 0 = | 1 = 1.
2. Purpose
Some bits of a data are set to 1.
3. Example: 9 | 5: 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. XOR operator (^)
It is also called the XOR operator.
1. Operation Rules
If the two binary carry numbers involved in the calculation are the same, the result is 0 (false); the difference is 1 (true), that is:
0 ^ 0 = 0 0 ^ 1 = 1 1 ^ 0 = 1 1 ^ 1 = 0.
2. Purpose
(1) enable specific positioning to flip
If there is 01111010, and you want to lower it by 4 bits, you can perform the ^ operation with 00001111.
(2) equal to 0 ^, retain the original value
(3) exchange two values without temporary variables
Suppose a = 3, B = 4. To swap values of A and B, use the following value assignment statement:
A = a ^ B; B = B ^ A; A = a ^ B;
3. 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. Inverse operators (~)
1. Operation Rules
~ It is a single object (Meta) operator used to reverse a binary number by bit, that is, to change 0 to 1, 1, and to 0.
2. Purpose
To set the percentile of an integer a to 0, use a = &~ 1;
3. For example ~ 9 is calculated as follows :~ (0000000000001001) Result: 1111111111110110

5. Left shift operator (<)
1. Operation Rules
This parameter is used to remove all binary numbers of a number from the left, and add 0 to the right, overflow after the high left shift, and discard does not work.
2. Purpose
Shifts one digit to the left, which is multiplied by 2.
3. 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 );

6. Right Shift Operator (>)
1. Operation Rules
It is used to shift all the binary numbers of a number to several places on the right, and the low position to the right is discarded. For the unsigned number, the high position is supplemented with 0;
For the number of symbols, move the left to 0 ("logical right shift") or 1 ("arithmetic right shift ")
2. Purpose
Shifts one digit to the right is equal to dividing by 2

VII. bitwise assignment operators
Bitwise operators and value assignment operators can form a composite value assignment operator, for example:
<=, |=, >=, <=, ^ =

8. bitwise operations for data of different lengths
If the two data lengths are different, when bitwise operations (for example, A & B, while a is long and B is int) are performed, the system will align the two to the right. If B is a positive number, the left 16 digits are filled with 0. If B is a negative number, the left end is filled with 1. If B is an unsigned integer, the left end is filled with 0.

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.ProgramPerform operations by domain name. 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.


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.

For example, if you select a moderate color, 1 indicates red, 2 indicates blue, 4 indicates black, and 8 indicates white.
1 = 0000 0001
2 = 0000 0010
4 = 0000 0100
8 = 0000 1000

If you select 2 and 4 (both red and black) then 1 (0000 0001) or 2 (0000 0010) or 4 (0000 0100) = 7 (0000 0101)
If 7 is provided to you, how do you know the options are 1, 2, and 4? The answer is: 7 And four numbers, 1, 2, and 4, respectively, or the result is 7, which indicates that a selected
For example, 7 or 2 = 7, so 1 is selected as 7 or 8 = 15, not 7, so 8 is not selected, so you should know the purpose.

The bit operation method is as follows:

operation name
calculation object type
calculation result type, object count instance ~ Bit logical non-operation
integer or numeric integer
1 ~ A & bitwise logic and arithmetic integer or complex type
integer 2 A & B | bitwise logic or arithmetic integer or complex integer 2 A | B ^
bitwise logic exclusive or arithmetic integer or complex type integer 1 ^ A bitwise shift operation integer or numeric integer 2 A> 2

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: 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.