CS210 · Block 4 · Lesson 34

Bitwise Operators I

Bitwise operators · Two's complement · Shifts · Set / clear / toggle / test a bit
At a glance: Down to the level of individual bits. You learn the six bitwise operators, the rule the machine uses to represent negative numbers (two's complement), and the four moves that turn those operators into tools: setting, clearing, toggling, and testing a single bit. Two walkthroughs in Section 5 build the intuition; the lab applies the four moves to a festival wristband. Class opens with Quiz 10, so the in-class time is tighter than usual.
Contents
  1. Lesson Objectives
  2. Assigned Readings
  3. Pre-Class Work
  4. Lesson Materials and Overview
  5. In-Class Work
  6. After Class
1. Lesson Objectives

By the end of this lesson, cadets will be able to:

  1. Apply bitwise AND, OR, XOR, NOT, and shift operators in C expressions. (Outcome 1)
  2. Explain how integers are represented in two's complement. (Outcome 1)
  3. Implement basic bit patterns to set, clear, toggle, and test individual bits. (Outcome 1)
2. Assigned Readings

Complete before class. These set the vocabulary we will use.

Source Sections Why
Beej-C Chapter 24 (Bitwise Operations) The six operators and how each one works on bits
King, C Programming: A Modern Approach Chapter 20 (Low-Level Programming), sections on bitwise operators Optional deeper dive into shifts and bit manipulation
3. Pre-Class Work
Do this first
Class opens with Quiz 10 (Recursion II and III) at the start of the period. Budget time to review that material as well as the new reading. The bitwise content moves fast once the quiz is done.

Pre-Class Checklist

1
Read Beej-C Chapter 24 (Bitwise Operations)
Get familiar with the six operators and what each one does to the bits:
  • & AND, | OR, ^ XOR, ~ NOT
  • Left shift << and right shift >>
  • Note the difference between bitwise & and logical &&
2
Review Recursion II and III for Quiz 10
Quiz 10 is the final quiz of the course and is given at the start of this lesson. It covers Lessons 32 and 33: recursion on dynamic structures, tracing recursive calls, and the tradeoffs between iteration and recursion. Review your notes and labs from those lessons.
3
Skim the In-Class section below
You will see two interactive walkthroughs: one on two's complement, one on the bitwise operators. No need to use them yet; just know they are there.
4. Lesson Materials and Overview

Back in Lesson 2 you saw that the same bits read differently as signed and unsigned. This lesson goes underneath that: the rule the machine uses to build negative numbers, and the operators that let you read and change bits one at a time. The reference material below covers what you will see in lecture and use in both walkthroughs.

Jump to
Slides Why bits The six operators Two's complement The four idioms Coding standard

Slides

The Lesson 34 deck covers the six operators, two's complement, the shifts, and the four single-bit idioms. The slides are the spine of the in-class lecture; the two walkthroughs are where you practice each idea hands-on.

Open Lesson 34 slides → replace href with your SharePoint link

Why work at the bit level

Most of the time you treat an integer as a single number. Sometimes it is more useful to treat it as a row of 16 or 32 independent switches. A single integer can track which permissions a user has, which options are turned on, or which sensors reported in, one bit per flag. Bitwise operators are how you read and flip those switches without disturbing the others.

This lesson is the fundamentals: the operators and the four basic moves. Lesson 35 builds on it with multi-bit masks and packing several values into one integer. Get the single-bit moves solid here and the next lesson is mostly review with bigger masks.

The six operators

Five take two operands; ~ takes one. They work bit by bit, position by position.

Operator Name A result bit is 1 when...
&ANDboth input bits are 1
|OReither input bit is 1
^XORthe two input bits differ
~NOTthe single input bit is 0 (it flips every bit)
<<left shifta bit slid into this position from the right (zeros fill in)
>>right shifta bit slid into this position from the left (low bits fall off)

Watch the doubles. & and && are different operators. Single & combines bits; double && is the logical AND that produces true or false. Same for | versus ||. Using the wrong one is a common and quiet bug.

Shifts as multiply and divide. On an unsigned value, x << n multiplies by 2n and x >> n divides by 2n (dropping the remainder), as long as nothing important falls off the end. We work in unsigned short in this lesson so the right shift is well defined; on signed values the behavior of >> is not guaranteed.

Two's complement

Two's complement is the rule almost every machine uses to represent signed integers. The headline: to negate a number, invert every bit and add one. That is the entire rule.

// start with 6 in a 16-bit short
6     = 0000000000000110
// step 1: invert every bit (~)
~6    = 1111111111111001  // this alone reads as -7
// step 2: add 1
~6 + 1 = 1111111111111010 = -6

The sign bit is a weight, not a flag. In a 16-bit signed value the top bit does not just mean negative; it carries the weight -215 = -32768. Every other bit adds its usual positive value. So 1111111111111111 is -32768 + 32767 = -1, and the all-ones pattern is always -1 in a signed type.

The range is lopsided. A short runs from -32768 to 32767. There is one more negative value than positive because zero takes one of the non-negative slots. That is why negating the most negative number gives you back the most negative number: its positive twin does not exist. The two's complement walkthrough in Section 5 lets you watch all of this happen bit by bit.

The four single-bit idioms

Almost everything you do with bits comes down to four moves on one bit at position n. Each one builds a single-bit mask with (1 << n) and combines it with the value. Memorize these four; the lab is built on them.

Move Expression Why it works
Setvalue | (1 << n)OR with a 1 forces that bit on; OR with the 0s elsewhere leaves them alone
Clearvalue & ~(1 << n)the mask is all 1s except bit n; AND forces only that bit off
Togglevalue ^ (1 << n)XOR with a 1 flips that bit; XOR with the 0s elsewhere leaves them alone
Test(value >> n) & 1slide bit n down to position 0, then mask it off; result is 1 if set, 0 if not

Coding standard for this lab

This lesson does not introduce new DFCS C Programming Standard rules, but the lab is a good place to keep the naming rules sharp. The perk flags are #define constants in SCREAMING_SNAKE_CASE (§5.6), the functions and variables are snake_case (§5.1, §5.2), and naming each perk with a #define instead of a bare number is exactly the rule against magic numbers (§7.1). The full standard is in the course Resources section.

5. In-Class Work

Class opens with Quiz 10 (Recursion II and III). After the quiz, work through both walkthroughs and then the lab. Use the checklist to track your progress.

  • Work through the two's complement walkthrough below. Nine guided tasks: negate a number by hand, see the sign bit as a weight, and watch the range run lopsided. About 15 minutes.
  • Work through the bit operations playground. Twelve guided tasks across the six operators and the four single-bit idioms. About 20 minutes.
  • Complete the lab: Festival Wristband Perks. Implement set, clear, toggle, test, and count on a wristband stored in one unsigned short. Auto-graded through GitHub Classroom; accept the assignment with the GitHub Classroom invite. Worth 2 points.

Two's Complement Walkthrough

Nine tasks across four sections. Build a negative number by hand, see why the high bit is a negative weight, and watch the range run one slot further negative than positive. When you finish, copy the completion code for the Lesson 34 reflection.

Before you begin

Enter your name. It will appear on the completion screen so you can include it in your screenshot for the Lesson 34 reflection.

CS210 Lesson 34 · Two's Complement Walkthrough

In Lesson 2 you saw that the same bits read differently as signed and unsigned. Now see the mechanism behind it: how a negative number is built (invert, then add one), why the high bit acts as a negative weight, and why the range is lopsided. Type the C statement or expression each task asks for; the right pane shows the bits.
Task 0 of 9
Section 1: The sign bit as a weight
Current task
Loading...
Binary view
Nothing yet.
Type a declaration on the left.
bits>
How this works: Declare a short or unsigned short to see its 16-bit pattern, plus how it reads as signed and unsigned. You can also negate by hand: type ~x to invert every bit (one's complement), or ~x + 1 to finish the negation. The sign bit (the highest bit of a signed type) is outlined in red.

Bit Operations Playground

Twelve tasks across three sections. Run each of the six operators, then build the four single-bit idioms (set, clear, toggle, test) yourself. When you finish, copy the completion code for the Lesson 34 reflection.

Before you begin

Enter your name. It will appear on the completion screen so you can include it in your screenshot for the Lesson 34 reflection.

CS210 Lesson 34 · Bit Operations Playground

Six operators, one bit at a time. Declare an unsigned short, then combine values with AND, OR, XOR, NOT, and the two shifts. The right pane shows both operands and the result, bit for bit. The last section drills the four moves you will use constantly: set, clear, toggle, and test a single bit.
Task 0 of 12
Section 1: AND, OR, XOR
Current task
Loading...
Operation view
Nothing yet.
Declare an unsigned short on the left.
bits>
How this works: Declare variables like unsigned short x = 42;, then type an expression. Operators: & AND, | OR, ^ XOR, ~ NOT, << left shift, >> right shift. You can combine them: x | (1 << 3). Operands can be variables or numbers. All values are 16-bit unsigned.
6. After Class
  • Finish the Festival Wristband lab if you did not complete it in class. Submit through GitHub Classroom.
  • Complete the Lesson 34 reflection in Blackboard. You will need both walkthrough completion codes and a screenshot of each completion screen.
  • Team PEX progress check is due around this lesson. Make sure your group has posted its status update.
  • Next lesson extends this into applied bitwise work: masks that touch several bits at once and packing multiple values into one integer. Lesson 35 reading is the provided supplementary notes.
Need help? Schedule EI with your instructor. Bring your specific code or a screenshot of the bit pattern you do not understand, plus the exact output or error message. Specific questions get unstuck quickly. The course Resources section has the DFCS C Programming Standard and the Git troubleshooting card for self-service reference.