Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Bit Manipulation Techniq | C Programming Fundamentals lesson | BraveProgrammer
  1. Courses
  2. /
  3. C Programming Fundamentals

Lesson 37 of 50

·c

Bit Manipulation Techniques

12 mins

Course progress74%

What you'll learn

Keep these ideas in mind as you work through the lesson.

4 points
  • Left‑shift `1U << n` creates a mask with only bit `n` set.
  • `x & (x-1)` clears the lowest set bit – great for counting ones.
  • Bitwise ops are defined for unsigned types; signed‑right‑shift is implementation‑defined.
  • Use `U` suffix for **unsigned** literals to avoid sign‑extension surprises.

Bit tricks are useful for flags, fast arithmetic, and low‑level protocols.

TaskExpression
Set bit n`x
Clear bit nx &= ~(1U << n);
Toggle bit nx ^= (1U << n);
Test bit n(x & (1U << n)) != 0
Count set bitsKernighan’s algorithm: while(x){x &= x-1; ++count;}
Is power of two?x && !(x & (x-1))

These operations are O(1) and often replace loops.


📚 Example: Counting Bits in an Unsigned Integer

unsigned int count_bits(unsigned int x) {
    unsigned int c = 0;
    while (x) {
        x &= x - 1; // clear least‑significant 1‑bit
        ++c;
    }
    return c;
}
Make it stickPractice what you've learned1 quiz · 3 practical tests · Optional activities from C Programming FundamentalsBrowse activities
Previous lessonSearching Algorithms – Linear & Binary SearchContinue to lesson 38Dynamic Memory – Reallocating ArraysBack to C Programming Fundamentals curriculum