Niels Robben
Niels Robben

Reputation: 1647

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

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?

Upvotes: 27

Views: 74070

Answers (4)

Jonathan Sacramento
Jonathan Sacramento

Reputation: 46

To flip bits, you can use the exclusive OR bitwise operator. This takes two operands (typically, the value you want to operate on and the mask defining what bits will be flipped). The eXclusive OR (XOR) operator will only flip a bit if, and only if, one of the two is set to 1, but NOT both. See the (simple) example below:

#include <stdio.h>

int main(int argc, char** argv)
{
   int num = 7;   //00000111
   int mask = 3;  //00000011

   int result = num ^ mask; //00000100
   printf("result = %d\n", result); //should be 4

   return 0;
}

Upvotes: 2

Eutherpy
Eutherpy

Reputation: 4571

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). :)

Upvotes: 6

AssafR
AssafR

Reputation: 61

First of all, good luck!

One remark - it is more useful to count the bits from the right and not left, since there are various byte/word sizes (8-bit,16-bit,etc.) and that count preserves compatibility better. So in your case you are referring to bits #7 and #4 (zero-count).

Did you mean 'flip' (change 0<->1 bits) or 'switch' them between one and the other?

For the first option, the answer above (XOR with "int mask = 0x90; // 10010000") is very good. For the second one, it's a bit more tricky (but not much).

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

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.

Upvotes: 42

Related Questions