CS210 · Block 4 · Lesson 35

Bitwise Operators II (Applied)

Bit masks · Field extraction · Clear-and-set · Packing · Systems and security idioms
At a glance: Lesson 34 gave you the bitwise operators; today you put them to work. You will pull a field out of a packed integer, replace one field without disturbing its neighbors, and pack several values into a single word. The running example is RGB565 color, and the lab has you build a full pixel packer. The two interactive widgets in Section 5 are where the masks and shifts become muscle memory.
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 bit masks to extract and modify specific bits within an integer. (Outcome 1)
  2. Pack multiple values into a single integer using bit masks and shifts. (Outcomes 1, 2)
  3. Recognize common bitwise idioms in systems and security contexts. (Outcome 1)
2. Assigned Readings

Complete before class. The reading for this lesson is a short set of course notes, not a Beej chapter. It pulls the applied techniques together in one place.

Source What it covers
Lesson 35 notes: Applied Bitwise Operators Masks, the extract / replace / pack idioms, single-bit flag tricks, the precedence trap, and a note on struct bit-fields. About 10 minutes.
Lesson 34 notes (review) If the six operators or two’s complement feel rusty, skim last lesson’s material first.
3. Pre-Class Work
Do this first
Read the Lesson 35 notes. They are short and they map one-to-one onto what you will do in class and in the lab.
1
Read the Lesson 35 notes
Focus on the three things you do with a field: extract (shift, then mask), replace (clear, then OR), and pack (mask, shift, OR). Those three moves are the whole lesson.
2
Confirm your toolchain is ready
You will compile a small multi-file program today. Make sure your gcc and your terminal are working so lab time goes to bit manipulation, not setup.
3
Skim the In-Class section below
Two interactive widgets are waiting there: a mask & pack walkthrough and a bitwise idioms self-check. No need to use them yet; just know they are there.
4. Lesson Materials and Overview

Lesson 34 was about what each bitwise operator does to individual bits. Today is about using them together to work with fields: named groups of bits packed inside one integer. The overview below is a quick reference; the full treatment is in the Lesson 35 notes, and the hands-on practice is in Section 5.

Jump to
Slides Fields and masks The three moves Idioms and traps DFCS standard

Slides

The Lesson 35 deck walks through masks, the extract / replace / pack idioms, the RGB565 layout, and the precedence traps. The slides are the spine of the lecture; the widgets are where you practice.

Open Lesson 35 slides →

Fields and masks

A field is a group of bits inside an integer that means something on its own. RGB565 packs a color into a 16-bit unsigned short as three fields:

bit:  15 14 13 12 11 | 10  9  8  7  6  5 |  4  3  2  1  0
      \____ red ____/  \_____ green _____/  \___ blue ___/
        5 bits           6 bits           5 bits

A mask is an integer whose bits you set deliberately so that & or | against it has a known effect. A field mask is the all-ones value for a field width, shifted into the field’s position. The green mask, six 1s at bits 10–5, is 0x3F << 5.

The three moves

Move Pattern Green field example
Extractshift, then mask(color >> 5) & 0x3F
Replaceclear, then OR(color & ~(0x3F<<5)) | ((g&0x3F)<<5)
Packmask, shift, OR((r&0x1F)<<11) | ((g&0x3F)<<5) | (b&0x1F)

Mask each incoming value with its field mask before you shift it into place. That one guard keeps an out-of-range value from spilling into a neighbor field, and the lab’s hidden tests check for exactly that habit.

Idioms and traps

When a field is a single bit (a flag), the moves shrink to one-liners: test with flags & m, set with flags |= m, clear with flags &= ~m, toggle with flags ^= m. You will meet these in permission bytes, hardware registers, and protocol headers.

The trap to remember: bitwise operators have low precedence, and comparison operators outrank &. So flags & MASK == 0 is parsed as flags & (MASK == 0), which is almost never what you meant. Always parenthesize: (flags & MASK) == 0. And keep & (bitwise) distinct from && (logical).

DFCS C Programming Standard

This lesson introduces no new sections of the DFCS C Programming Standard. The lab reinforces habits you already hold yourself to: the named field constants in color.h keep magic numbers out of your code (§7.1), those constants follow the SCREAMING_SNAKE_CASE convention for macros (§5.4 / §5.6), and your functions and variables stay in snake_case (§5.1). As always, the build runs with -Wall -Werror, so a warning is a failure, not a suggestion. The full standard lives in the course Resources section.

5. In-Class Work

Three things to do in class. Use the checklist to track your progress. The two widgets each give you a completion code for the Lesson 35 reflection.

  • Work through the mask & pack walkthrough below. Ten guided tasks: extract a field, build a mask, clear and replace a field, then pack three values into one word. About 20 minutes.
  • Take the bitwise idioms self-check. Eight questions on permission bits, packed color, flag registers, and the precedence trap. Score 70 percent or higher for the passing code. About 10 minutes.
  • Complete Lab 35: Pixel Packer (RGB565). Build the seven RGB565 functions. Auto-graded through GitHub Classroom; full instructions in the lab repo. Worth 2 points.

Mask & Pack Walkthrough

Ten tasks across four sections. Type each expression at the prompt; the right pane shows the color word, the result, and how the fields decode. The variable color is pre-loaded.

Before you begin

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

CS210 Lesson 35 · Mask & Pack Walkthrough

A 16-bit color word holds three fields at once: red, green, and blue. Type C expressions to pull a field out, clear it, drop a new value in, and pack three values into one integer. The right pane shows the bits and decodes the fields.
Task 0 of 10
Section 1: Extract a field
Current task
Loading...
Color word & result
Type an expression on the left.
expr>
RGB565 layout: a 16-bit unsigned short holds red in the top 5 bits (15–11), green in the middle 6 bits (10–5), and blue in the low 5 bits (4–0). The variable color is pre-loaded. Type any expression using color, numbers (decimal or 0x hex), and the operators & | ^ ~ << >>. Parentheses work. Remember C precedence: shifts bind tighter than &, which binds tighter than |.

Bitwise Idioms Self-Check

Eight questions on the patterns you meet in real systems and security code. Answer each, submit, and move on. The score card gives you your completion code.

Before you begin

Enter your name. It will appear with your completion code on the score card so you can include it in your screenshot for the Blackboard reflection.

CS210 Lesson 35 · Bitwise Idioms Self-Check

Eight questions on the bit patterns you meet in real systems and security code: permission bits, packed color, flag registers, and the precedence traps that turn a one-character slip into a silent bug. Answer each, submit, and move forward.
How this works: One question per card. Pick your answer and click Submit. Feedback appears, then click Next. Answers lock once submitted, so think before you submit. Score 70 percent or higher to earn the passing completion code for the Lesson 35 reflection.
6. After Class
  • Finish Lab 35 if you did not complete it in class. Commit and push through GitHub Classroom before Lesson 36.
  • Complete the Lesson 35 reflection in Blackboard. Enter both widget completion codes and answer the reflection prompt.
  • Replay the walkthrough in free mode. Try packing a color of your own, then extract each field back out and confirm you get your inputs.
  • Next up: Lesson 36 introduces function pointers, the last big idea in functional decomposition.
Need help? Schedule EI with your instructor. Bring the specific expression or function that is not behaving, the value you put in, and the value you got out. A field that comes out wrong is almost always a shift or a mask off by a few bits; print the value in binary and line it up against the layout.