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

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. C Programming Fundamentals

Lesson 37 of 50 · c

Bit Manipulation Techniques

Duration: 12 mins

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;
}
Previous: Searching Algorithms – Linear & Binary SearchNext: Dynamic Memory – Reallocating Arrays