Skip to main content

Lesson 2 of 5

Bitwise Operations - Masking, Setting & Shifting

Bitwise operators work directly on the binary representation of integers. They are used in embedded programming for manipulating hardware register bits, in graphics for colour packing, in networking for IP address manipulation, and in data compression. Every C programmer must know the six bitwise operators and the core bit-manipulation idioms.

13 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Bitwise Operators - All Idioms & Real Applications

Bitwise Operators - All Idioms & Real Applications
#include <stdio.h>
#include <stdint.h>

/* ── Six bitwise operators ───────────────────────────────────
   &   AND: both bits 1 → 1                              0101 & 0011 = 0001
   |   OR:  either bit 1 → 1                             0101 | 0011 = 0111
   ^   XOR: bits differ → 1                              0101 ^ 0011 = 0110
   ~   NOT (complement): flip all bits                   ~0101 = ...11111010
   <<  Left shift:  x<<n = x * 2^n (check for overflow)
   >>  Right shift: x>>n = x / 2^n (arithmetic on signed)     */

/* ── Core idioms: Set, Clear, Toggle, Test ─────────────── */
#define BIT_SET(v, n)    ((v) | (1U << (n)))      /* set bit n   */
#define BIT_CLEAR(v, n)  ((v) & ~(1U << (n)))     /* clear bit n */
#define BIT_TOGGLE(v, n) ((v) ^ (1U << (n)))      /* toggle bit n*/
#define BIT_TEST(v, n)   (((v) >> (n)) & 1U)      /* check bit n */

/* ── Packed RGBA colour ──────────────────────────────────── */
typedef uint32_t Color;
#define COLOR_RGBA(r,g,b,a) ((Color)((r)<<24|(g)<<16|(b)<<8|(a)))
#define COLOR_R(c)  (((c)>>24)&0xFF)
#define COLOR_G(c)  (((c)>>16)&0xFF)
#define COLOR_B(c)  (((c)>>8) &0xFF)
#define COLOR_A(c)  ( (c)     &0xFF)

/* ── Power-of-two checks ─────────────────────────────────── */
int is_power_of_two(unsigned int n) {
    return n > 0 && (n & (n - 1)) == 0;
}

/* ── Round up to next power of 2 ────────────────────────── */
uint32_t next_pow2(uint32_t n) {
    if (n == 0) return 1;
    n--;
    n |= n >> 1;  n |= n >> 2;
    n |= n >> 4;  n |= n >> 8;
    n |= n >> 16;
    return n + 1;
}

/* ── Swap without temporary (XOR trick) ────────────────── */
void swap_xor(int *a, int *b) {
    /* Only works when a != b! If a==b, result is 0 (bug). */
    *a ^= *b;
    *b ^= *a;
    *a ^= *b;
}

int main(void) {
    uint8_t flags = 0;         /* 00000000 */
    flags = BIT_SET(flags, 2); /* 00000100 = 4 */
    flags = BIT_SET(flags, 5); /* 00100100 = 36 */
    printf("flags = 0x%02X
", flags);          /* 0x24 */
    printf("bit 2 = %u
", BIT_TEST(flags, 2)); /* 1 */
    printf("bit 3 = %u
", BIT_TEST(flags, 3)); /* 0 */
    flags = BIT_CLEAR(flags, 2);
    printf("cleared bit 2: 0x%02X
", flags);   /* 0x20 */

    /* Colour packing */
    Color red = COLOR_RGBA(255, 0, 0, 255);
    printf("red=0x%08X R=%u G=%u B=%u A=%u
",
           red, COLOR_R(red), COLOR_G(red), COLOR_B(red), COLOR_A(red));

    printf("is_pow2(16)=%d  is_pow2(18)=%d
", is_power_of_two(16), is_power_of_two(18));
    printf("next_pow2(13)=%u
", next_pow2(13));  /* 16 */

    printf("1<<0=%d 1<<4=%d 1<<31=%u
", 1<<0, 1<<4, 1U<<31);

    int a=5, b=9;
    swap_xor(&a, &b);
    printf("after swap: a=%d b=%d
", a, b);  /* a=9 b=5 */

    return 0;
}

Common Mistakes

  • Shifting by more than or equal to the bit width - `1 << 32` on a 32-bit `int` is undefined behaviour. Use `1U << 31` (unsigned) for the highest bit of a 32-bit value; `1ULL << 63` for 64-bit.
  • XOR swap when `a == b` - `if (a == b) return;` is required before XOR swap. When `a` and `b` point to the same variable: `*a ^= *b` makes it 0, then both become 0.
  • Using signed integers for bitwise operations - right-shifting a negative signed integer is implementation-defined in C (may be arithmetic or logical). Always use unsigned types (`uint32_t`, etc.) for bitwise work.

Tip

Tip

Practice Bitwise Operations Masking Setting Shifting in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Bitwise operations manipulate individual bits for hardware registers, permissions, and flags

Practice Task

Note

Practice Task - (1) Write a working example of Bitwise Operations Masking Setting Shifting from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Bitwise Operations Masking Setting Shifting is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready c code.

Key Takeaways

  • Bitwise operators work directly on the binary representation of integers.
  • Shifting by more than or equal to the bit width - `1 << 32` on a 32-bit `int` is undefined behaviour. Use `1U << 31` (unsigned) for the highest bit of a 32-bit value; `1ULL << 63` for 64-bit.
  • XOR swap when `a == b` - `if (a == b) return;` is required before XOR swap. When `a` and `b` point to the same variable: `*a ^= *b` makes it 0, then both become 0.
  • Using signed integers for bitwise operations - right-shifting a negative signed integer is implementation-defined in C (may be arithmetic or logical). Always use unsigned types (`uint32_t`, etc.) for bitwise work.

Topics in This Module

0/5 done