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.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). :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With