How to flip a specific bit in a byte in C?

Niels Robben picture Niels Robben · Oct 27, 2013 · Viewed 38.1k times · Source

I'm trying to use masks and manipulating specific bits in a byte. For example:

I want to write a program in C that flips two bits at particular positions e.g. the bit at position 0 and the one at the third position. So, 11100011, would become 01110011.

How can I swap these bits?

Answer

Sergey Kalinichenko picture Sergey Kalinichenko · Oct 27, 2013

Flipping a bit is done by XOR-ing with a mask: set bits at the positions that you want to flip, and then execute a XOR, like this:

int mask = 0x90; // 10010000
int num  = 0xE3; // 11100011
num ^= mask;     // 01110011

Here are a few notes:

  1. bits are commonly counted from the least significant position, so your example flips bits in positions 4 and 7, not at positions 0 and 4
  2. To construct a bit mask for a single position, use expression 1 << n, where n is the position number counting from the least significant bit.
  3. To combine multiple bits in a single mask, use | operator. For example, (1 << 4) | (1 << 7) constructs the mask for flipping bits 4 and 7.