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?
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 << n
, where n
is the position number counting from the least significant bit.|
operator. For example, (1 << 4) | (1 << 7)
constructs the mask for flipping bits 4 and 7.