You make a classic mistake thinking that fewer lines in C mean more optimized code.
You should really check the assembler output and profile your code to see if this is really a bottleneck.
What I usually do is optimize for readability, and then only attack performance if that becomes a problem. So a more readable solution (in my not very humble opinion) would be something like this:
unsigned int bit_swap (unsigned int num, unsigned int pos1, unsigned int pos2) { // Swapping identical bit positions is a no-op. if (pos1 == pos2) return num; // Get masks from bit positions. unsigned int mask1 = 1 << pos1; unsigned int mask2 = 1 << pos2; // Get bit truth values. int bit1_was_set = ((num & mask1) != 0); int bit2_was_set = ((num & mask2) != 0); // Clear and set first bit (set only if second bit was originally set). num = num & ~mask1; if (bit2_was_set) num = num | mask1; // Do the same for other bit. num = num & ~mask2; if (bit1_was_set) num = num | mask2; // Return the value with swapped bits. return num; }
Although you have a lot more lines than your approach, you can find the insanely optimizing compilers currently available will provide you with similar code under the covers.
What you will almost certainly find is that people who are not C-gurus (and perhaps themselves in six months) will be able to better understand your source code than the option with several bit operations with one line.
source share