LearnFrenzy
Sign in Take a free test

C Programming · Topic 14 of 23

Bitwise Operators

  • 4 exercises
  • 40 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Bitwise Operators · Study material

Bitwise operators in C work on the individual bits of integers. They are how C sets hardware registers, packs flags into one byte, encodes colours and network headers, and powers fast tricks such as checking for a power of two in one line. They are also full of traps: shifts that are undefined, operator precedence that surprises everyone, and small types that are silently promoted to int. This page explains the operators, the masks and the traps, then gives you 40 practice questions checked with UndefinedBehaviorSanitizer.

On this page

  • The six operators: & | ^ ~ << >>
  • Masks: set, clear, toggle and test a bit
  • Which shifts are undefined, and why unsigned types are safer
  • Precedence and promotion traps, and C23's binary literals

The six bitwise operators

OperatorNameBit result12 op 10
&AND1 only if both bits are 11100 & 1010 = 1000 (8)
|OR1 if either bit is 11110 (14)
^XOR1 if the bits differ0110 (6)
~NOTflips every bit~12 flips all 32 bits
<<left shiftmoves bits left, fills with 012 << 2 = 48
>>right shiftmoves bits right12 >> 2 = 3
#include <stdio.h>

int main(void) {
    unsigned a = 12, b = 10;                 /* 1100 and 1010 */
    printf("a & b  = %u\n", a & b);           /* 1000 */
    printf("a | b  = %u\n", a | b);           /* 1110 */
    printf("a ^ b  = %u\n", a ^ b);           /* 0110 */
    printf("~a & 0xF = %u\n", ~a & 0xF);      /* 0011: ~ flips all 32 bits, keep the low 4 */
    printf("a << 2 = %u, a >> 2 = %u\n", a << 2, a >> 2);
    return 0;
}

Output

a & b  = 8
a | b  = 14
a ^ b  = 6
~a & 0xF = 3
a << 2 = 48, a >> 2 = 3

Masks: set, clear, toggle and test

A mask is a value with 1s exactly where you want to act. 1u << k is a mask for bit k.

GoalCode
Set bit kx |= 1u << k;
Clear bit kx &= ~(1u << k);
Toggle bit kx ^= 1u << k;
Test bit k(x >> k) & 1u
#include <stdio.h>

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

int main(void) {
    unsigned char flags = 0;
    flags |= 1u << 3;          /* set bit 3    */  print_bits(flags);
    flags |= 1u << 0;          /* set bit 0    */  print_bits(flags);
    flags ^= 1u << 7;          /* toggle bit 7 */  print_bits(flags);
    flags &= ~(1u << 3);       /* clear bit 3  */  print_bits(flags);
    printf("bit 0 is %u\n", (flags >> 0) & 1u);    /* test bit 0   */
    return 0;
}

Output

00001000
00001001
10001001
10000001
bit 0 is 1

Shifts: the undefined cases

Shifts are where most bitwise bugs hide. The C standard says:

  • Shifting by a negative amount, or by at least the width of the type (32 or more for a 32-bit int), is undefined behaviour.
  • Left-shifting a negative value, or shifting a 1 into or past the sign bit of a signed type (1 << 31), is undefined.
  • Right-shifting a negative value is implementation-defined (GCC and Clang copy the sign bit).

The fix is simple: do bit work on unsigned types – unsigned, uint32_t, uint8_t – and write masks as 1u << k.

Two traps: precedence and promotion

&, ^ and | have lower precedence than ==, so x & 1 == 0 means x & (1 == 0) – always 0. Always bracket: (x & 1) == 0. And every type smaller than int is promoted to int before an operation, so ~ on an unsigned char 0x0F gives the int −16, not 0xF0. Cast back ((unsigned char) ~c) when you want 8 bits.

What C23 adds

C23 brings binary literals (0b1010, long supported by compilers and now standard), digit separators (0b1111'0000, 1'000'000), and the <stdbit.h> header with portable bit functions such as stdc_count_ones(), stdc_bit_width() and stdc_has_single_bit() (available in newer C libraries, e.g. glibc 2.39+).

#include <stdio.h>

int main(void) {
    unsigned mask = 0b1111'0000;          /* C23: binary literal with a digit separator */
    unsigned long big = 1'000'000;        /* C23: separators make long numbers readable */
    printf("%u %lu\n", mask, big);
    return 0;
}

Output

240 1000000

Key points to remember

  • Use unsigned types for bit manipulation; write masks as 1u << k.
  • Never shift by ≥ the type's width or by a negative amount.
  • Bracket every bitwise expression inside a comparison.
  • &/| are bitwise; &&/|| are logical – they are not interchangeable.
  • x ^ x == 0, x ^ 0 == x, and n & (n - 1) removes the lowest 1 bit.

Frequently asked questions

What is the difference between & and &&?

& combines the bits of two integers. && is a logical AND that gives 0 or 1 and stops early if the left side is false. 2 & 1 is 0, but 2 && 1 is 1.

Is x << 1 the same as x * 2?

For unsigned values (and non-negative signed values that do not overflow), yes. Compilers already turn x * 2 into a shift, so write whichever is clearer.

Why are bitwise operators used in embedded systems?

Hardware registers pack many settings into the bits of one word; masks let a program change one setting without disturbing the others.

Where can I learn more?

Read Bitwise Operators in C and Operators in C, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About C Programming

C programming is the language most computer science courses start with and the foundation of operating systems, embedded devices and compilers. This section helps you learn C properly – data types, operators, control statements, functions, arrays, strings, pointers, structures, memory allocation and files – and then prove it with hundreds of practice questions explained line by line.

Why it matters

  • C teaches how a computer really works: memory, addresses and how data is stored
  • Pointers and memory questions are a favourite in written tests and technical interviews
  • Once you know C, learning C++, Java and Python becomes much easier
  • Embedded systems, operating systems and many companies' coding rounds still use C

Who it is for

  • School students (Class 11–12 computer science) building a strong programming base
  • College students (B.Tech, BCA, MCA, B.Sc CS) preparing for semester exams, lab work and viva
  • Freshers preparing for campus placements, aptitude-cum-coding tests and technical interviews
  • Anyone preparing for GATE CS or government IT exams

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • TCS, Infosys, Wipro tests
  • Technical interviews
  • GATE CS
  • University exams
  • Government IT exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links