C: Bitwise Operations

🗓 Last updated: 2026-11-30👤 Written by: Harper✓ Reviewed by: MOTO🏷 Category: C Tutorial

Bitwise operations are like controlling a row of light switches — each light corresponds to one bit, and you can turn on, turn off, or flip any individual light without affecting the others.

1. Binary Review

Computers represent all data internally using binary. One byte = 8 bits, each bit is 0 or 1.

TEXT
Decimal 42  =  Binary 00101010
Decimal 255 =  Binary 11111111

Signed integers use two's complement representation: the highest bit is the sign bit, 0 for positive, 1 for negative.

C
Decimal  5  =  00000101
Decimal -5  =  11111011  (two's complement)

2. Six Bitwise Operators

Operator Name Rule
& Bitwise AND Result is 1 only when both bits are 1
| Bitwise OR Result is 1 when at least one bit is 1
^ Bitwise XOR Result is 1 when the two bits differ
~ Bitwise NOT 0 becomes 1, 1 becomes 0
<< Left shift Shifts bits left, fills low bits with 0
>> Right shift Shifts bits right, fills high bits with sign bit (signed) or 0 (unsigned)

(1) Bitwise AND (&)

TEXT
  1010  (10)
& 1100  (12)
------
  1000  (8)

Uses: clearing certain bits, checking whether certain bits are 1.

(2) Bitwise OR (|)

C
  1010  (10)
| 1100  (12)
------
  1110  (14)

Uses: setting certain bits to 1.

(3) Bitwise XOR (^)

TEXT
  1010  (10)
^ 1100  (12)
------
  0110  (6)

Properties: a ^ a = 0, a ^ 0 = a. XOR is reversible — XORing twice with the same value restores the original.

(4) Bitwise NOT (~)

C
~ 00101010  (42)
= 11010101  (-43, two's complement)

For unsigned numbers: ~0 = 255 (8-bit), ~0 = 0xFFFFFFFF (32-bit).

(5) Left Shift (<<)

TEXT
5 << 2
= 00000101 << 2
= 00010100
= 20

Left shifting by n is equivalent to multiplying by 2^n. 5 << 2 = 5 * 4 = 20.

(6) Right Shift (>>)

C
20 >> 2
= 00010100 >> 2
= 00000101
= 5

Right shifting by n is equivalent to dividing by 2^n (rounded toward zero).

⚠️ Note: Right-shifting signed negative numbers fills high bits with 1 (arithmetic shift), which may produce unexpected results. It's recommended to only shift unsigned values.


3. Four Essential Bit Operations

(1) Set a Bit (to 1)

TEXT
flags |= (1 << n);

Sets the nth bit to 1, leaving all other bits unchanged.

(2) Clear a Bit (to 0)

C
flags &= ~(1 << n);

~(1 << n) produces a mask that is all 1s except for a 0 at the nth position. ANDing clears only that bit.

(3) Toggle a Bit

TEXT
flags ^= (1 << n);

XOR operation: 0^1=1, 1^1=0, which perfectly implements toggling.

(4) Check a Bit

C
// Conditional check
if (flags & (1 << n)) {
}

If the nth bit is 1, the result is non-zero; if 0, the result is zero.

▶ Example

▶ Try it Yourself
TEXT
Set bit 3: 00001000
Set bit 5: 00101000
Clear bit 3: 00100000
Toggle bit 5: 00000000
Toggle bit 7: 10000000
Bit 7 is 1

4. Mask Techniques

A mask is a predefined combination of bits used to extract or modify specific bit fields within data.

(1) Extract Low Bits

C
unsigned int val = 0xABCD;
unsigned int low_byte = val & 0xFF;

0xFF is a mask that keeps only the lowest 8 bits.

(2) Extract High Bits

TEXT
unsigned int high_byte = (val >> 8) & 0xFF;

First shift right by 8 bits, then mask to get the low 8 bits.

(3) Combine Values

C
unsigned int combined = (high << 8) | low;

Join two bytes into a 16-bit value.

▶ Example

RGB color value extraction. A 24-bit color value has 8 bits each for red, green, and blue:

▶ Try it Yourself
TEXT
Color #FF6633:
  Red: 255
  Green: 102
  Blue: 51
Darkened: #7F3319
💡 Tip: RGB color extraction is a classic application of bitwise operations. In web development, the #RRGGBB format is essentially a 24-bit integer — red in bits 16-23, green in bits 8-15, blue in bits 0-7.


5. Permission Flags

Linux file permissions are a classic application of bitwise operations. 9 permission bits represent owner/group/other for read/write/execute:

C
rwxr-xr-x = 111101101 = 0755
rw-r--r-- = 110100100 = 0644
C
// Preprocessor directive
#include <stdio.h>

// Preprocessor directive
#define READ    (1 << 2)
// Preprocessor directive
#define WRITE   (1 << 1)
// Preprocessor directive
#define EXECUTE (1 << 0)

// Function definition
void show_permission(unsigned char perm) {
    // I/O operation
    printf("%c", (perm & READ) ? 'r' : '-');
    // I/O operation
    printf("%c", (perm & WRITE) ? 'w' : '-');
    // I/O operation
    printf("%c", (perm & EXECUTE) ? 'x' : '-');
}

// Function definition
int main(void) {
    unsigned char owner  = READ | WRITE | EXECUTE;
    unsigned char group  = READ | EXECUTE;
    unsigned char other  = READ | EXECUTE;

    // I/O operation
    printf("Permissions: ");
    show_permission(owner);
    show_permission(group);
    show_permission(other);
    // I/O operation
    printf("\n");

    owner &= ~WRITE;
    // I/O operation
    printf("After removing write: ");
    show_permission(owner);
    show_permission(group);
    show_permission(other);
    // I/O operation
    printf("\n");

    // Return result
    return 0;
}
TEXT
Permissions: rwxr-xr-x
After removing write: r-xr-xr-x

6. Practical Bit Tricks

(1) Swap Two Variables (Without a Temporary)

C
a ^= b;
b ^= a;
a ^= b;

Principle: the self-inverse property of XOR. However, this hurts readability and is not recommended in real development.

(2) Check Odd or Even

TEXT
if (n & 1) {
}

If the lowest bit is 1, the number is odd. This is faster than n % 2.

(3) Multiply/Divide by Powers of 2

C
n << 1
n << 2
n >> 1

Compilers typically optimize n * 2 into a shift, but shifts are only safe for positive integers.

(4) Compute Powers of 2

TEXT
unsigned int pow2 = 1u << n;

1u << 0 = 1, 1u << 1 = 2, 1u << 8 = 256... Shifting is much faster than pow(2, n).

(5) Align to a Power of 2

C
unsigned int aligned = (value + mask) & ~mask;

For example, align to a 4-byte boundary: (n + 3) & ~3.

C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) {
    int values[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    // For loop
    for (int i = 0; i < 10; i++) {
        // Variable declaration
        int aligned = (values[i] + 3) & ~3;
        // I/O operation
        printf("%d -> %d\n", values[i], aligned);
    }
    // Return result
    return 0;
}
TEXT
0 -> 0
1 -> 4
2 -> 4
3 -> 4
4 -> 4
5 -> 8
6 -> 8
7 -> 8
8 -> 8
9 -> 12

❓ FAQ

Q How to set, clear, and toggle a single bit?
A Set bit n with x |= (1 << n). Clear bit n with x &= ~(1 << n). Toggle bit n with x ^= (1 << n). Check if bit n is set with (x & (1 << n)) != 0. The pattern 1 << n creates a mask with only bit n set.
Q Why are shift operations faster than multiplication and division?
A Shifts are single-cycle CPU instructions, while multiplication and division require multiple clock cycles. Modern compilers automatically optimize multiplication by powers of 2 into shifts, so you do not normally need to write them manually.
Q What happens if you shift beyond the number of bits?
A Undefined behavior. Shifting a 32-bit int by 32 or more bits is not allowed by the C standard. The behavior depends on the compiler — some implementations return the original value, some crash. Always ensure the shift count is between 0 and sizeof(type) times 8 minus 1.
Q Can bitwise operations be used on floating-point numbers?
A No. Bitwise operators only work on integer types. To manipulate the bits of a floating-point number, you need to copy its bytes to an integer using memcpy, do the bitwise work there, then copy back.
Q What is wrong with the XOR swap?
A If both variables point to the same memory (e.g., the same location), the XOR swap zeroes out the value — a = a ^ a becomes 0, then b = 0 ^ 0 stays 0. Plus, it is hard to read and the compiler optimizes a regular swap to be just as efficient.
Q With arrays, why is it the case that a[5] == 5[a]?
A Because in C, a[5] is syntactic sugar for *(a + 5), and 5[a] is *(5 + a). Addition is commutative, so they evaluate to the exact same memory location. This is a consequence of how C arrays degrade to pointers.
Q Is less than faster than less than or equal?
A No. On modern CPUs, < and <= compile to the same comparison instruction (cmp) followed by a different branch condition. The actual comparison cost is identical; only the branch flags differ, and the compiler handles this.
Q Difference between malloc and calloc?
A malloc(bytes) allocates uninitialized memory — the contents are whatever was left there before. calloc(n, element_size) allocates n times element_size bytes and zeroes every byte. calloc is slightly slower but is the right choice for bit arrays that depend on clean zero initialization.

▶ Example — permission flags with bit masks

▶ Try it Yourself
TEXT
Has read
Flags: 5 (read=1 write=0 exec=1)

📖 Summary

📝 Exercises

  1. Write a function that returns the number of 1-bits in an integer's binary representation (using bitwise operations, not dividing by 2 in a loop)
  2. Write a program that uses bitwise operations to adjust the brightness of an RGB color (multiply each channel by a coefficient and recombine)
  3. Write a function that extracts bits m through n from a 32-bit integer (m < n, counting from bit 0)
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏