Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to calculate the inverse mask for an unsigned char

I would like to calculate an inverse mask for an unsigned char.meaning if the original mask 0xc0 the the inverse mask should be 0x3f.that is to say all the bits should be flipped or inverted.I have tried the below but doesn't seem to be working.

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 I get are mask 0x3 inv mask 0xff

I cannot seem to find the bug in my code.

like image 272
liv2hak Avatar asked Nov 04 '11 01:11

liv2hak


People also ask

How do I make a bitmask in C++?

For example, consider a set in which s = {1, 2, 5, 8, 6, and 7}. To represent the set of {2, 5, 7}, we can use any bitmask 010110. This is done by considering a value 'x'. We can perform x|=x<<i for setting a bit.

What is bitmask in c++?

Bitmask also known as mask is a sequence of N -bits that encode the subset of our collection. The element of the mask can be either set or not set (i.e. 0 or 1). This denotes the availability of the chosen element in the bitmask. For example, an element i is available in the subset if the ith bit of mask is set.

What is mask in bit manipulation?

A mask defines which bits you want to keep, and which bits you want to clear. Masking is the act of applying a mask to a value. This is accomplished by doing: Bitwise ANDing in order to extract a subset of the bits in the value.


1 Answers

Why can't you just do this:

uint8_t mask = 0x03;
uint8_t inverse_mask = ~mask;
like image 88
Mysticial Avatar answered Sep 28 '22 09:09

Mysticial