invert bit programme in c++ coding

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.

unsigned char x = J
int p = 3
int n = 5
New character = t

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
unsigned char x = *
int p = 5
int n = 2
New character = &


  • Is it your home work which you want us to complete?
  • Is it your home work which you want us to complete?
  • [color=Blue]Bits are inverted with XOR operation. In C (or C++) this operator looks like this character => ^:[/color]
    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.
    [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:
    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
    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:

    Go by link: "Machine Level Operations". This section has bits operations that you need.
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!