# Bitwise operations in C ++

Source: Internet
Author: User
When I first went to the company for a written test a few days ago, I ran into several bitwise operations. I was just reading C ++ primer and happened to see bitwise operations. So I went online to search for the next article. Article To study it!

What is bit )?

Bit is a single 0 or 1, and bit is the basis for everything we do on the computer. All data on the computer is stored in bits. A byte is composed of eight characters. A word is two or sixteen bytes, and a DWORD is two or twelve characters. As follows:

0 1 0 0 0 1 1 1 1 0 0 0 1 1 1 0 1 1 1 1 0 1 0 0 0 1 1 1 0 0 0

|

| +-Bit 31 | bit 0-+ |

|

+ -- Byte 3 -----+ ---- byte 2 --- + ---- byte 1 --- + --- byte 0 ----- +

|

+ ------------ Word 1 ------------ + ----------- word 0 ------------- +

|

+ ----------------------------- DWORD ----------------------------- +

The advantage of bitwise operations is that byte, word, or DWORD can be used as a small array or Structure . You can use bitwise operations to check bitwise values or assign values, or perform operations on the entire bitwise group.

Hexadecimal number and its relationship with bit

The value represented by 0 or 1 is the binary number, which is hard to understand. Therefore, the hexadecimal number is used.

The hexadecimal number uses four digits to represent the value of 0-15. The four digits form a hexadecimal number. Also, the four digits are converted into a half byte (nibble ). A byte has two nibble values. Therefore, two hexadecimal numbers can be used to represent a byte. As follows:

Nibble Hex Value

====================

0000 0

0001 1

0010 2

0011 3

0100 4

0101 5

0110 6

0111 7

1000 8

1001 9

1010

1011 B

1100 C

1101 d

1110 E

1111 F

If you use a byte to store the letter "R" (ASCII code 114), the result is:

0111 binary

It can be expressed as '0x72'

There are 6 bit operations:

& Operation

| Or operation

^ Exclusive or operation

~ Non-computation (complement)

> Right shift operation

<Left shift operation

And operations (&)

Binary operations. When both the two locations are set to 1, the result is equal to 1, and other results are equal to 0.

1 & 1 = 1

1 & 0 = 0

0 & 1 = 0

0 & 0 = 0

One purpose of the operation is to check whether the position is equal to 1 ). For example, if a byte contains a flag, check whether the 4th bits are set, Code As follows:

Byte B = 50;

If (B & 0x10)

Cout <"bit four is set" <Endl;

Else

Cout <"bit four is clear" <Endl;

The above code can be expressed:

00110010-B

& Amp; 00010000-& 0x10

----------------------------

00010000-Result

We can see that 4th bits are set.

Or (|)

Binary operations. If one of the two locations is set to one, the result is equal to 1. If both of them are 0, the result is 0.

1 | 1 = 1

1 | 0 = 1

0 | 1 = 1

0 | 0 = 0

And operations can also be used to check the placement. For example, to check whether 3rd bits of a value are set:

Byte B = 50;

Byte c = B | 0x04;

Cout <"c =" <C <Endl;

The table can be:

00110010-B

| 00000100-| 0x04

----------

00110110-Result

XOR (^)

Binary operations. If two digits are not equal, the result is 1; otherwise, the result is 0.

1 ^ 1 = 0

1 ^ 0 = 1

0 ^ 1 = 1

0 ^ 0 = 0

The exclusive or operation can be used to flip bitwise values. For example, flip the values of 3rd and 4th bits:

Byte B = 50;

Cout <"B =" <B <Endl;

B = B ^ 0x18;

Cout <"B =" <B <Endl;

B = B ^ 0x18;

Cout <"B =" <B <Endl;

The table can be:

00110010-B

^ 00011000-^ 0x18

----------

00101010-Result

00101010-B

^ 00011000-^ 0x18

----------

00110010-Result

Non-computation (~)

Single Object operation. The bitwise value is reversed. Set 0 to 1 or 1 to 0. The purpose of Non-computation is to clear 0 and 1 for the rest. Non-calculation is not related to the value size. For example, clear the 1st and 2nd bits to 0, and the remaining positions are 1:

Byte B = ~ 0x03;

Cout <"B =" <B <Endl;

Word W = ~ 0x03;

Cout <"W =" <W <Endl;

The table can be:

00000011-0x03

11111100 -~ 0x03 B

0000000000000011-0x03

1111111111111100 -~ 0x03 W

The combination of non-operation and operation ensures that the value is 0. For example, clear the 4th bits to 0:

Byte B = 50;

Cout <"B =" <B <Endl;

Byte c = B &~ 0x10;

Cout <"c =" <C <Endl;

The table can be:

00110010-B

& Amp; 11101111 -~ 0x10

----------

00100010-Result

Shift operation (>>and <)

Moves the bit value to a specified number of digits. Shift right> the operator moves from the high position to the low position, and moves left <The operator moves from the low position to the high position. Usually shift is used to align the positions (such as makewparam, hiword, and loword macro functions ).

Byte B = 12;

Cout <"B =" <B <Endl;

Byte c = B <2;

Cout <"c =" <C <Endl;

C = B> 2;

Cout <"c =" <C <Endl;

The table can be:

00001100-B

00110000-B <2

00000011-B> 2

All of the preceding examples are correct, but the examples may not be used properly. Please read the article at the end of the article and explain it clearly.

Bit Field)

A meaningful thing in BIT operations is bit domain. Byte, word, or DWORD can be used to create a minimal data structure. For example, to save the date data and try Decrease Memory usage, you can declare this structure:

Struct date_struct {

Byte day: 5, // 1 to 31

Month: 4, // 1 to 12

Year: 14; // 0 to 9999

} Date;

In the structure, the date data occupies a minimum of 5 digits, the month occupies 4 digits, and the year occupies 14 digits. In this way, the entire date data only takes up to 23 bytes. Ignore the 24th bits. If an integer is used to express each field, the entire structure occupies 12 bytes.

| 0 0 0 0 0 0 0 0 | 0 0 0 0 0 0 0 0 | 0 0 0 0 0 0 0 0 |

|

+ ------------- Year -------------- + month + -- day -- +

Now let's take a look at what happened in this structure declaration.

First, let's take a look at the data types used by the bit domain structure. Here byte is used. One byte has eight digits. the compiler will allocate one byte of memory. If the data in the structure exceeds 8 bits, the compiler will allocate another byte until the data requirements are met. If you use word or DWORD as the Data Type of the structure, the compiler allocates a complete 32-bit memory to the structure.

Next, let's take a look at the domain declaration. The variable name (day, month, year) follows a colon, followed by the number of digits occupied by the variable. Fields are separated by commas and ended with semicolons.

With the bit domain structure, you can easily process member data as you would with common structured data. Although we cannot get the address of the bit domain, we can use the structure address. For example:
Date. Day = 12;
Dateptr = & date;
Dateptr-> year = 1852;

Using shift operations to avoid multiplication is a common technique, but the multiplier must be a positive integer and at least one must be 2 to the nth power, for example, 2, 4, 8, 16, 32 ...... The feature of the shift operation is that the speed is fast, while the multiplication operation is slow. The conversion of the multiplication operation to the shift operation can be slightly improved.ProgramOperation Efficiency. For example:

Num * = 32;
Equivalent
Num <= 5;/* 2 is equal to 32 x */

If the multiplier is not the nth power of 2, we can divide the multiplier into the sum of the nth power of 2:
Num * = 20;
Equal
Num * = (16 + 4 );
Equal
Num = num * 16 + num * 4;
Equal
Num = (Num <4) + (Num <2 );

However, the current compilers are very clever and they will do this optimization in place of us. That is to say, if the statement we write is:
Num * = 100;
The compiler optimizes the statement:
Num = (Num <6) + (Num <5) + (Num <2 );

Therefore, we do not need to perform this optimization manually because the compiler will complete it for us. In addition, even with this optimization, the speed will not be greatly improved. We should focus on improvingAlgorithmA good algorithm can greatly improve the program running efficiency!

Related Keywords:
Related Article

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.