I'm working on a practice problem for my C programming class where we need to use bitwise operations. The task is to create a program that complements all bits in an unsigned binary integer `x`, except for the least significant bit (LSB). Currently, my code only works for integers ending in 1 but not for those that end in 0. I'm wondering if I must use if-statements, or if this can be achieved solely with bitwise operators. This is what I have so far: `temp = x & 1; // store LSB
x = ~x;
x = temp | x;` Looking for guidance on how to approach this!
3 Answers
When you invert a number, a zero at the end becomes a one. Remember that a bitwise OR will only add bits, not remove them. This means you need to handle that last bit carefully.
You can absolutely solve this with only bitwise operators! Just ensure you manage the last bit correctly by toggling it right before the final calculation. A compound statement could achieve this in one line if you set it up appropriately. The key will be figuring out a way to flip just the LSB without disturbing the others.
You’ve nailed fetching the last bit! Instead of using if-statements, focus on manipulating your complemented value directly. You could either clear the last bit before inverting bits or set it to 1 and then complement the rest. Think about how you can achieve that using just bitwise operations!

So I need a way to toggle the LSB while flipping the others, right? I’ve heard of XOR but I’m not sure how it fits into this. Could you explain its application here?