CodeBlanks Logo Icon CodeBlanks

Bit hacks

  • C course
  • Intermediate
  • Lesson 103/116
  • 5 min

Learn fast bit hacks and tricks.

Swap with XOR

You can swap two variables without a temporary using three XOR operations. This is known as the XOR swap.

Example: a ^= b; b ^= a; a ^= b;. After three steps, a and b exchange values. In the first step a becomes a ^ b. In the second step b gets the old value of a. In the third step a gets the old value of b. Though cool, on modern CPUs swapping with a temporary is faster; XOR swap is more of a curiosity and an embedded trick.

min with ternary

Bitwise operations are often combined with the ternary operator (?:). It is a short way to assign a conditional value in one line.

Example: int min = (a < b) ? a : b;. Here, if a < b is true, min becomes a; otherwise b. This is shorter than writing if-else. Combined with bit hacks it is a powerful tool; for instance, after an XOR swap you can find the smaller value in one line. Ternary is ideal for producing conditional values in expression context and in macros.

Practice Write XOR swap and min

Declare int a = 7, b = 3;. Swap with a ^= b; b ^= a; a ^= b;. Print with printf("a=%d b=%d\n", a, b);. Compute int min = (a < b) ? a : b;. Print with printf("min=%d\n", min);.

Starter code

main.c
#include <stdio.h>

// Define a=7 and b=3
// Swap with XOR
// Print the values
// Compute min with ternary and print

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int main(void) {
    int a = 7, b = 3;
    a ^= b; b ^= a; a ^= b;
    printf("a=%d b=%d\n", a, b);
    int min = (a < b) ? a : b;
    printf("min=%d\n", min);
    return 0;
}

Expected output

a=3 b=7
min=3

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How many steps does the XOR swap take?

  • One
  • Two
  • Three Correct answer
  • Four

Explanation: The XOR swap uses three ^= operations.

2 Match the bit hacks

Term Meaning
a ^= b XOR swap step
(a<b)?a:b Smaller value
^ Bitwise XOR
?: Ternary

3 Complete the XOR swap

Question
a ^= b; b ^= a; a ^= ____;
Answer
a ^= b; b ^= a; a ^= b;

Explanation: In the third step a ^= b; gives a the old value of b.

All lessons in Intermediate