0
0
CHow-ToBeginner · 3 min read

How to Use Bitwise AND Operator in C: Syntax and Examples

In C, the bitwise AND operator is &. It compares each bit of two integers and returns a new integer where each bit is 1 only if both bits in the operands are 1. Use it like result = a & b; to get the bitwise AND of a and b.
📐

Syntax

The bitwise AND operator in C is &. It takes two integer operands and compares their bits one by one.

  • Operands: Two integers (int, char, etc.)
  • Operator: & placed between operands
  • Result: Integer with bits set to 1 only where both operands have 1
c
result = a & b;
💻

Example

This example shows how to use the bitwise AND operator to compare bits of two numbers and print the result.

c
#include <stdio.h>

int main() {
    int a = 12;  // binary: 1100
    int b = 10;  // binary: 1010
    int result = a & b;  // bitwise AND

    printf("a = %d, b = %d\n", a, b);
    printf("a & b = %d\n", result);  // expected 8 (1000 in binary)

    return 0;
}
Output
a = 12, b = 10 a & b = 8
⚠️

Common Pitfalls

Common mistakes when using bitwise AND in C include:

  • Using & instead of && for logical AND (they are different operators).
  • Applying bitwise AND to non-integer types without casting.
  • Expecting decimal addition instead of bitwise operation.

Example of wrong vs right usage:

c
#include <stdio.h>

int main() {
    int x = 5;  // binary 0101
    int y = 3;  // binary 0011

    // Wrong: using logical AND instead of bitwise AND
    int wrong = x && y;  // evaluates to 1 because both are non-zero

    // Right: bitwise AND
    int right = x & y;   // evaluates to 1 (0001 in binary)

    printf("Logical AND (x && y) = %d\n", wrong);
    printf("Bitwise AND (x & y) = %d\n", right);

    return 0;
}
Output
Logical AND (x && y) = 1 Bitwise AND (x & y) = 1
📊

Quick Reference

Bitwise AND (&) Quick Tips:

  • Use & between two integers to compare bits.
  • Result bit is 1 only if both bits are 1.
  • Different from logical AND && which works on true/false.
  • Commonly used for masking bits or checking flags.

Key Takeaways

The bitwise AND operator in C is & and works on bits of integers.
It returns a number with bits set to 1 only where both operands have 1 bits.
Do not confuse bitwise AND & with logical AND &&.
Use bitwise AND for tasks like masking bits or checking specific flags.
Operands must be integers; applying to other types requires casting.