04. Bitwise Operators & Bit Manipulation in C

🟡 Difficulty: Intermediate | Binary Bit Logic, Bitmasks & Hardware Registers

📖 Definition

Bitwise operators in C operate directly on the individual binary bit representations (0s and 1s) of integer operands (such as char, short, int, uint8_t, uint32_t). C provides six bitwise operators: & (Bitwise AND), | (Bitwise OR), ^ (Bitwise XOR), ~ (Bitwise NOT / One's Complement), << (Left Shift), and >> (Right Shift).

🎯 Why It Is Used

  • Embedded Systems & Hardware Drivers: Directly manipulating microcontroller registers (setting, clearing, or toggling individual pin bits).
  • Compact Flag Enums: Storing up to 32 boolean permission flags in a single 4-byte uint32_t variable.
  • High-Speed Cryptography & Network Protocols: Packet header parsing, checksum calculations, and hardware encryption routines.

⚙️ How It Works: The 4 Core Bit Manipulation Idioms

Mastering bit manipulation in C relies on four standard bitmask operations on a variable flags at bit position n:

  1. Set Bit n (Turn ON): flags |= (1U << n);
  2. Clear Bit n (Turn OFF): flags &= ~(1U << n);
  3. Toggle Bit n (Flip 0/1): flags ^= (1U << n);
  4. Test Bit n (Check State): bool is_set = (flags & (1U << n)) != 0;

📝 Syntax & Bitwise Operators Table

Operator Name Operation Rule Example (a=5 / 0101, b=3 / 0011)
&Bitwise AND1 if BOTH corresponding bits are 1; else 0a & b → 0001 (1)
|Bitwise OR1 if AT LEAST ONE corresponding bit is 1; else 0a | b → 0111 (7)
^Bitwise XOR1 if corresponding bits are DIFFERENT; else 0a ^ b → 0110 (6)
~Bitwise NOTInverts all bits (0 → 1, 1 → 0)~a → 1010... (-6)
<<Left ShiftShifts bits left by k positions (Multiplies by 2k)a << 1 → 1010 (10)
>>Right ShiftShifts bits right by k positions (Divides by 2k)a >> 1 → 0010 (2)

🔀 Right Shift Behavior: Signed vs Unsigned Integers

In ISO C, right-shifting an unsigned integer performs a zero-extension Logical Right Shift (padding 0s on the left). Right-shifting a negative signed integer is Implementation-Defined in C (most compilers perform sign-extension Arithmetic Right Shift). For predictable bit manipulation, always use unsigned integer types (like uint8_t, uint32_t)!

🌱 Beginner Example

#include <stdio.h>
#include <stdint.h>

int main(void) {
    uint8_t x = 12; // Binary: 0000 1100
    uint8_t y = 10; // Binary: 0000 1010

    printf("x & y = %u (00001000 = 8)\n", x & y);
    printf("x | y = %u (00001110 = 14)\n", x | y);
    printf("x ^ y = %u (00000110 = 6)\n", x ^ y);
    printf("x << 2 = %u (00110000 = 48)\n", x << 2);
    printf("x >> 1 = %u (00000110 = 6)\n", x >> 1);
    return 0;
}

🌼 Intermediate Example: Practical Bitmask Operations

#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>

#define FLAG_READ    (1U << 0) // Bit 0 (0x01)
#define FLAG_WRITE   (1U << 1) // Bit 1 (0x02)
#define FLAG_EXECUTE (1U << 2) // Bit 2 (0x04)

int main(void) {
    uint8_t permissions = 0;

    // 1. Set Read and Write permissions
    permissions |= FLAG_READ | FLAG_WRITE;
    printf("Permissions byte after setting READ and WRITE: 0x%02X\n", permissions);

    // 2. Check if EXECUTE permission is granted
    bool can_execute = (permissions & FLAG_EXECUTE) != 0;
    printf("Can Execute? %s\n", can_execute ? "Yes" : "No");

    // 3. Clear WRITE permission
    permissions &= ~FLAG_WRITE;
    printf("Permissions byte after clearing WRITE: 0x%02X\n", permissions);

    // 4. Toggle EXECUTE permission
    permissions ^= FLAG_EXECUTE;
    printf("Permissions byte after toggling EXECUTE: 0x%02X\n", permissions);
    return 0;
}

🌲 Advanced Example: Printing Binary Representation & Fast Power-of-Two Test

#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>

void print_binary8(uint8_t val) {
    for (int i = 7; i >= 0; i--) {
        printf("%c", (val & (1U << i)) ? '1' : '0');
        if (i % 4 == 0 && i != 0) printf(" ");
    }
    printf("\n");
}

bool is_power_of_two(uint32_t n) {
    // Fast bitwise trick: A number is a power of 2 if (n & (n - 1)) == 0
    return (n > 0) && ((n & (n - 1)) == 0);
}

int main(void) {
    uint8_t num = 173;
    printf("Decimal %u in 8-bit Binary: ", num);
    print_binary8(num);

    uint32_t test1 = 64, test2 = 70;
    printf("%u is power of 2? %s\n", test1, is_power_of_two(test1) ? "Yes" : "No");
    printf("%u is power of 2? %s\n", test2, is_power_of_two(test2) ? "Yes" : "No");
    return 0;
}

🔍 Line-by-Line Explanation

  • permissions |= FLAG_READ;: Sets bit 0 to 1 without altering other bit flags.
  • permissions &= ~FLAG_WRITE;: Inverts mask (0xFF → 0xFD) and ANDs it to clear bit 1 to 0.
  • (n & (n - 1)) == 0: Bitwise trick for powers of 2. Powers of 2 have exactly one 1-bit; subtracting 1 flips that bit and all lower bits to 1, making their bitwise AND result 0.

💻 Expected Terminal Output

Permissions byte after setting READ and WRITE: 0x03
Can Execute? No
Permissions byte after clearing WRITE: 0x01
Permissions byte after toggling EXECUTE: 0x05
Decimal 173 in 8-bit Binary: 1010 1101
64 is power of 2? Yes
70 is power of 2? No

⚠️ Common Mistakes & Pitfalls

  • Shifting by Bit Width or Greater: Shifting a 32-bit integer by 32 positions or more (e.g. x << 32) is Undefined Behavior in C!
  • Shifting Negative Numbers: Left-shifting a negative signed integer is Undefined Behavior in C. Always use unsigned integer types.
  • Precedence Confusion: Bitwise operators have lower precedence than relational operators (e.g. x & 1 == 0 evaluates 1 == 0 first!). Always wrap bitwise expressions in parentheses: (x & 1) == 0.

📌 Important Rules & Limitations

  • Always use unsigned integer types (uint8_t, uint32_t) for bit manipulation.
  • Always enclose bitwise mask operations in parentheses when combining with relational or logical operators.

🌐 Multilingual Explanation: English

Bitwise operators manipulate individual bits. Use |= to set bits, &= ~mask to clear bits, and ^= to toggle bits. Always use unsigned integers to avoid signed right-shift implementation-defined behaviors.

🌐 Multilingual Explanation: Hindi (Roman Script)

Bitwise operators direct 0s aur 1s par kaam karte hain. Bit set karne ke liye |=, clear karne ke liye &= ~mask, aur toggle karne ke liye ^= use karein. Bit manipulation ke liye hamesha unsigned types use karein.

🌐 Multilingual Explanation: Marathi (Roman Script)

Bitwise operators bit level var kaam kartat. Bit ON karnyasathi |=, OFF karnyasathi &= ~mask, aani toggle karnyasathi ^= vapartat. Hamesha unsigned integer types vapra.

❓ Practice Questions

  1. What is the standard C expression to clear bit position 3 in a uint8_t variable?
  2. Why is (x & (x - 1)) == 0 used to test if a number is a power of 2?
  3. Why should bitwise shift operations be performed on unsigned integers instead of signed integers?

🚀 Practical Coding Challenge

Write a C program named ip_mask_calculator.c that takes an IP address byte and a subnet mask byte (e.g. 192 and 255) and uses bitwise AND (&) to compute and display the network address byte in binary and decimal format.

🧭 Navigation & Breadcrumbs

← Previous: 03. Logical Operators | Module 05 Guide | Next: 05. Assignment Operators →