Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 955
Niels Robben Avatar asked Oct 27 '13 10:10

Niels Robben


2 Answers

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.
like image 60
Sergey Kalinichenko Avatar answered Sep 26 '22 00:09

Sergey Kalinichenko


If your byte is x, and you want to switch the bits at the i-th and j-th position:

x = x ^ ((1<<i) | (1<<j)); 

So, in your case, it would just be (1<<4) | (1<<7). :)

like image 26
Eutherpy Avatar answered Sep 24 '22 00:09

Eutherpy