CC
AdvancedLesson 16 of 18

Bit Operations & Fixed-Width Integer Types – C

Setting, clearing and testing bits; packing flags and color values; stdint.h.

Operators: & (and), | (or), ^ (xor), ~ (negation), << and >> (shifting). They work bitwise – unlike && and ||. Typical uses: flags in a byte, hardware registers, protocols, hashes, compact data structures.

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

#define FLAG_LESEN      (1u << 0)
#define FLAG_SCHREIBEN  (1u << 1)
#define FLAG_AUSFUEHREN (1u << 2)

int main(void) {
    uint8_t rechte = 0;
    rechte |= FLAG_LESEN | FLAG_SCHREIBEN;   // set bits
    rechte &= ~FLAG_SCHREIBEN;               // clear bit
    rechte ^= FLAG_AUSFUEHREN;               // toggle bit
    printf("%d\n", rechte);                  // 1 + 4 = 5
    printf("read: %d\n", (rechte & FLAG_LESEN) != 0);          // 1
    printf("write: %d\n", (rechte & FLAG_SCHREIBEN) != 0);  // 0
    return 0;
}

To print and count bits, you use loops and shifts. The trick x & (x - 1) clears the lowest set bit – so you count set bits in only as many steps as there are set bits:

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

void print_bits(uint8_t x) {
    for (int i = 7; i >= 0; i--) putchar(((x >> i) & 1) ? '1' : '0');
    putchar('\n');
}

int popcount(uint32_t x) {
    int n = 0;
    while (x) { x &= x - 1; n++; }
    return n;
}

int main(void) {
    print_bits(5);                    // 00000101
    print_bits(5 << 2);               // 00010100  (5 * 4 = 20)
    print_bits(0xF0 >> 4);            // 00001111
    printf("%d %d\n", popcount(255), popcount(1024));   // 8 1
    return 0;
}

Packing several values into one number is common, e.g. RGB colors in 24 bits. With shifting and masking, you extract them again:

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

int main(void) {
    uint32_t farbe = 0xFF8800;                 // RRGGBB
    uint8_t r = (farbe >> 16) & 0xFF;
    uint8_t g = (farbe >> 8) & 0xFF;
    uint8_t b = farbe & 0xFF;
    printf("%d %d %d\n", r, g, b);             // 255 136 0

    uint32_t neu = ((uint32_t)10 << 16) | ((uint32_t)20 << 8) | 30;
    printf("0x%06X\n", (unsigned)neu);         // 0x0A141E
    return 0;
}
WarningNever shift by as many bits as the type is wide or more (1 << 32 with a 32-bit int), and never by negative values – undefined behavior. Left-shifting into the sign bit is also problematic. Use unsigned types for bit operations (1u << 3, uint32_t).
TipUse <stdint.h> (uint8_t, int32_t, uint64_t) when the exact width matters (file formats, network protocols, hardware). For indices and sizes, size_t is the right type.