I want to calculate the inverse mask for an unsigned char

I would like to calculate the inverse mask for unsigned char.meaning, if the source mask is 0xc0, the inverse mask should be 0x3f. This means that all bits must be inverted or inverted. I tried the following but it doesn't seem to work.

int flipBit(int x, unsigned char position)
{
  int mask = 1 << position;
  return x ^ mask;
}

int main(int argc , char* argv[])
{
        uint8_t mask = 0x03;
        uint8_t inverse_mask = 0;
        uint8_t temp = 0;
        int loop = 0;

        for (loop = 0; loop < 8 ; loop ++)
        {
                temp = flipBit(mask,loop);
                inverse_mask |= temp;
        }
        printf("mask 0x%x inv mask 0x%x \n",mask,inverse_mask);
        return 0;
}

The results obtained mask 0x3 inv mask 0xff

I can not find the error in my code.

+5
source share
5 answers

Use the ~ (bitwise) operator.

inverse_mask = ~mask;
+6
source

Why can't you just do this:

uint8_t mask = 0x03;
uint8_t inverse_mask = ~mask;
+6
source

XOR.

uint8_t mask = 0x03;
uint8_t inverse_mask = mask ^ 0xFF;
+1

flipBit , :

0x03 ^ 0x01 = 0x02
0x03 ^ 0x02 = 0x01
0x03 ^ 0x04 = 0x07
0x03 ^ 0x08 = 0x0b
0x03 ^ 0x10 = 0x13
0x03 ^ 0x20 = 0x23
0x03 ^ 0x40 = 0x43
0x03 ^ 0x80 = 0x83
0x2 ^ 0x1 ^ 0x7 ^ 0xb ^ 0x13 ^ 0x23 ^ 0x43 ^ 0x83 = 0xff

int flipBit(uint8_t x, unsigned char position)
{
  int mask = 1 << position;
  return (x & mask) ^ mask;
}
+1

.

, :

x = 01110110

, "" :

y = 10001001

:

  • y - x
    • C : y = ~x;
    • , xor 1 , y = x^0xFF;
  • 1, . y+x == 0xFF
    • , y = 0xFF-x;

, , :

loop: 0
  mask:         0000 0011
  temp:         0000 0010
  inverse_mask: 0000 0010
loop: 1
  mask          0000 0011
  temp          0000 0001
  inverse_mask: 0000 0011
inverse_mask eventually: 0xFF

: inverse_mask, .

, temp , , flibBit, :

return x ^ mask;

:

return (x & mask) ^ mask;

, .

, , , .

+1

All Articles