I'm currently learning C with "The C Programming Language" from K&R. I solved the exercise 2-7, which says:
Write a function
invert(x,p,n)
that returnsx
with then
bits that begin at positionp
inverted (i.e., 1 changed into 0 and vice versa), leaving the other bits unchanged.
Here is my code (I voluntarily used chars here):
#include <stdio.h>
#define NUMBER 235
#define POSITION 2
#define AMOUNT 4
unsigned invert(unsigned char x, char p, char n)
{
unsigned char bitsToInvert = 0, i;
for (i = 1; i < n; i++) { // Make a number n-bits width, full of 1
bitsToInvert |= 1;
bitsToInvert <<= 1;
}
bitsToInvert |= 1;
bitsToInvert <<= p;
x ^= bitsToInvert;
return x;
}
int main()
{
printf("%d\n", invert(NUMBER, POSITION, AMOUNT));
}
Is there any optimisation I could bring to my code? Especially on the for
loop which create a number of n
1 bits?
Thanks!