liveBook · Manning

Bit operation

As explained in Modern C, Third Edition

A bitwise operator is a C operator that computes independently on corresponding bits of integer operands.

A bit operation applies an operator to the corresponding bits of integer operands. Treating each bit as a truth value makes & resemble logical AND, | resemble logical OR, and ^ represent exclusive OR; ~ complements every bit. Unlike && and ||, bitwise operators do not short-circuit. section 5.7.2

Representing a set with bits

Each corvid receives a distinct power-of-two constant, so one bit identifies each member. |= adds a member, while & tests membership.\n\n #define FLOCK_MAGPIE 1U\n #define FLOCK_RAVEN 2U\n #define FLOCK_JAY 4U\n #define FLOCK_CHOUGH 8U\n #define FLOCK_EMPTY 0U\n\n unsigned flock = FLOCK_EMPTY;\n\n if (something) flock |= FLOCK_JAY;\n\n if (flock & FLOCK_CHOUGH)\n do_something_chough_specific(flock);\n\nThe same operations correspond to set union, intersection, symmetric difference, and complement when bits represent set membership. section 5.7.2

C23 adds named bit operations in <stdbit.h> for unsigned integers, including counting one-bits, detecting a single set bit, finding bit width, and finding the highest-numbered singleton bit. These functions define results for every argument value, including exceptional cases, although a platform might not yet provide the header. section 5.7.2 section 8.2

How Modern C, Third Edition covers it

How deep it goes
Explains per-bit behavior, set correspondences, short-circuit differences, and C23 utilities, but not hardware implementation.
Examples
Uses corvid flock masks, binary and hexadecimal bit tables, and C23 <stdbit.h> function examples.
What it assumes
Assumes integer values and basic C expressions, while introducing bitwise meaning through truth-value and set analogies.
What you can do after
Apply it via C operators and <stdbit.h> functions to construct, update, test, and analyze bit sets.
How it connects
Connects bitwise operators with logical operators, unsigned integers, bit sets, and C23 integer arithmetic utilities.

Also explained in

Compare how 6 books explain bit operation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.