Читаем C++ Primer Plus полностью

The expression !x has the value 0. To see the value of ~x, you write it in binary form: 00000011. Then you convert each 0 to 1 and each 1 to 0. This produces the value 11111100, which in base 10 is the value 252. (Figure E.3 shows a 16-bit example.) The new value is termed the complement of the original value.

Figure E.3. The bitwise negation operator.

The bitwise OR operator (|) combines two integer values to produce a new integer value. Each bit in the new value is set to 1 if one or the other, or both, of the corresponding bits in the original values is set to 1. If both corresponding bits are 0, then the final bit is set to 0 (see Figure E.4).

Figure E.4. The bitwise OR operator.

Table E.1 summarizes how the | operator combines bits.

Table E.1. The Value of b1 | b2

The |= operator combines the bitwise OR operator with assignment:

a |= b;  // set a to a | b

The bitwise XOR operator (^) combines two integer values to produce a new integer value. Each bit in the new value is set to 1 if one or the other, but not both, of the corresponding bits in the original values is set to 1. If both corresponding bits are 0 or both are 1, the final bit is set to 0 (see Figure E.5).

Figure E.5. The bitwise XOR operator.

Table E.2 summarizes how the ^ operator combines bits.

Table E.2. The Value of b1 ^ b2

The ^= operator combines the bitwise XOR operator with assignment:

a ^= b;  // set a to a ^ b

The bitwise AND operator (&) combines two integer values to produce a new integer value. Each bit in the new value is set to 1 only if both of the corresponding bits in the original values are set to 1. If either or both corresponding bits are 0, the final bit is set to 0 (see Figure E.6).

Figure E.6. The bitwise AND operator.

Table E.3 summarizes how the & operator combines bits.

Table E.3. The Value of b1 & b2

The &= operator combines the bitwise AND operator with assignment:

a &= b;  // set a to a & b

Alternative Representations of Bitwise Operators

C++ provides alternative representations of several bitwise operators, as shown in Table E.4. They are provided for locales that do not have the traditional bitwise operators as part of their character sets.

Table E.4. Bitwise Operator Representations

These alternative forms let you write statements like the following:

b = compl a bitand b;  // same as b = ~a & b;

c = a xor b;           // same as c = a ^ c;

A Few Common Bitwise Operator Techniques

Often controlling hardware involves turning particular bits on or off or checking their status. The bitwise operators provide the means to perform such actions. We’ll go through the methods quickly.

In the following examples, lottabits represents a general value, and bit represents the value corresponding to a particular bit. Bits are numbered from right to left, beginning with bit 0, so the value corresponding to bit position n is 2n. For example, an integer with only bit number 3 set to 1 has the value 23 or 8. In general, each individual bit corresponds to a power of 2, as described for binary numbers in Appendix A. So we’ll use the term bit to represent a power of 2; this corresponds to a particular bit being set to 1 and all other bits being set to 0.

Turning a Bit On

The following two operations each turn on the bit in lottabits that corresponds to the bit represented by bit:

lottabits = lottabits | bit;

lottabits |= bit;

Each sets the corresponding bit to 1, regardless of the former value of the bit. That’s because ORing 1 with either 0 or 1 produces 1. All other bits in lottabits remain unaltered. That’s because ORing 0 with 0 produces 0, and ORing 0 with 1 produces 1.

Toggling a Bit

The following two operations each toggle the bit in lottabits that corresponds to the bit represented by bit. That is, they turn the bit on if it is off, and they turn it off if it is on:

lottabits = lottabits ^ bit;

lottabits ^= bit;

XORing 1 with 0 produces 1, turning an off bit on, and XORing 1 with 1 produces 0, turning an on bit off. All other bits in lottabits remain unaltered. That’s because XORing 0 with 0 produces 0, and XORing 0 with 1 produces 1.

Turning a Bit Off

The following operation turns off the bit in lottabits that corresponds to the bit represented by bit:

lottabits = lottabits & ~bit;

Перейти на страницу:

Все книги серии Developer's Library

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных

Похожие книги

1С: Бухгалтерия 8 с нуля
1С: Бухгалтерия 8 с нуля

Книга содержит полное описание приемов и методов работы с программой 1С:Бухгалтерия 8. Рассматривается автоматизация всех основных участков бухгалтерии: учет наличных и безналичных денежных средств, основных средств и НМА, прихода и расхода товарно-материальных ценностей, зарплаты, производства. Описано, как вводить исходные данные, заполнять справочники и каталоги, работать с первичными документами, проводить их по учету, формировать разнообразные отчеты, выводить данные на печать, настраивать программу и использовать ее сервисные функции. Каждый урок содержит подробное описание рассматриваемой темы с детальным разбором и иллюстрированием всех этапов.Для широкого круга пользователей.

Алексей Анатольевич Гладкий

Программирование, программы, базы данных / Программное обеспечение / Бухучет и аудит / Финансы и бизнес / Книги по IT / Словари и Энциклопедии
1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

Алексей Анатольевич Гладкий

Финансы / Программирование, программы, базы данных