Write a program that inverts n bits from the given position p of 8 bit representation of an input character x. Method invertBit takes 3 parameters x (the 8 bit input character), p as position where to start the inverting operation and n as the number of bits which needs to be inverted. Finally, you have to return the resultant characters after inverting the bits.
example:-
Input
________________________________________
unsigned char x = J
int p = 3
int n = 5
Output
________________________________________
New character = t
explanation:
Bit Representation of 'J' = 01001010, after inverting the bit from 3 to 5 positions the bit representation is 01110100. The character for the new bit is 't'. Hence 't' is the output
Example 2
Input
________________________________________
unsigned char x = *
int p = 5
int n = 2
Output
________________________________________
New character = &
Comments
[code]
int value = 0x6B9A;
int mask = 0xFFFF;
value ^= mask;
//
// This ^^^ will invert ALL bits in value. If mask has a bit=1, then
// corresponding bit in value will be inverted after XOR operation.
// If bit in mask=0, then this bit will be not inverted, but left
// alone.
//
[/code]
[color=Blue]All you need to do is build a mask of bits, at positions, where inversion is required. For example, if you need to invert 4 bits and position is 3 - this is your mask in binary:
0000 0000 0111 1000
You see here 3 zeroes at the left - it is a position. After this you see 4 bits set to 1.
But how to build the mask dynamically for all cases? Simple, you need to use OR operation (in C it is: | ) to set bits and LEFT SHIFT operation (in C it is: << ) to move the mask left by position p.
The algorithm to make a mask looks like that:
[/color]
[code]
mask = 0;
bit1 = 1;
position = p; // bit position, where to begin inverting
nbits = n; // number of bits to invert
repeat nbits times
shift mask to the left by 1 bit
mask = mask OR bit1
end repeat
shift mask to the left by position bits
[/code]
Now, after mask is built - you need to perform a XOR operation on your initial value and you get the output value.
Take a look at this C tutorial:
[link=http://www.iu.hio.no/~mark/CTutorial/CTutorial.html]http://www.iu.hio.no/~mark/CTutorial/CTutorial.html[/link]
Go by link: "Machine Level Operations". This section has bits operations that you need.