CodeBlanks Logo Icon CodeBlanks

Summary - Advanced bitwise

  • C course
  • Intermediate
  • Lesson 105/116
  • 5 min

Combine masking, shifting and hacks to write a permission system.

Bitwise operation summary

In this summary you'll combine masking, setting, shifting and packing into one program. The program places bits into a raw value, then extracts the components with shift and mask.

The structure: you add bits to raw with |= (using shift). Then you extract those bits back with >> and &. This simulates a real hardware register: you write flags to it, then parse them when reading. One integer carries both identity and state; this is the basis of memory savings in embedded systems.

Practice Write the bitwise summary program

Declare unsigned int raw = 0;. Place five shifted left by one with raw |= (5 << 1);. Set the first bit with raw |= 1;. Print with printf("raw=%u\n", raw);. Extract the id with unsigned int id = (raw >> 1) & 0x0F;. Get the active bit with unsigned int active = raw & 1;. Print with printf("id=%u active=%u\n", id, active);.

Starter code

main.c
#include <stdio.h>

// Define raw as 0
// Add bits with |= (using shift)
// Extract id and active values
// Print the results

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int main(void) {
    unsigned int raw = 0;
    raw |= (5 << 1);
    raw |= 1;
    printf("raw=%u\n", raw);
    unsigned int id = (raw >> 1) & 0x0F;
    unsigned int active = raw & 1;
    printf("id=%u active=%u\n", id, active);
    return 0;
}

Expected output

raw=11
id=5 active=1

Summary

In this group you learned advanced bitwise operations. You saw masking, setting and clearing bits, shifting, bit hacks and pack/unpack. You combined them to write a program that carries identity and state in one integer.

Bitwise operations appear everywhere from embedded systems to network protocols. Packing multiple values in one integer saves memory and bandwidth. In the next groups, typedef for type abstraction and finally the intermediate final project await you. Bitwise skill is essential for low-level programming.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which operation sets a bit?

  • &=
  • >>
  • |= Correct answer
  • ^

Explanation: |= sets the bit to 1 with bitwise OR.

2 Match the bitwise operations

Term Meaning
|= Set bit
&= Clear bit
<< Shift left
& 0x0F Low four bits

All lessons in Intermediate