How do Bitmasks work?

What are Bitmasks?

In computer science, a mask is data that is used for bitwise operations. Essentially it is a variable.

They are very often used in C programs.

Bit operators

These are the bit operators:

  • ~ Bitwise NOT (not to be confused with Logical NOT ‘!’)
  • & Bitwise AND (not to be confused with Logical AND ‘&&’)
  • | Bitwise OR (again, not to be confused with Logical OR ‘||’)
  • ^ Bitwise XOR
  • << Bitwise left shift
  • >> Bitwise right shift

This is how the operators work:

Bit A Bit B A & B A | B A ^ B ~A A << B A >> B
0 0 0 0 0 1 0 0
0 1 0 1 1 1 0 0
1 0 0 1 1 0 1 1
1 1 1 1 0 0 2 0

Some examples

Lets say I have any variable named “variable” with 32 bit.

Get the last bit:

return variable & 1;

Get the first bit:

return variable >> 31;

Get the bits 4 – 14 (11 bits):

return (variable  >> 4) & ((1<<11) - 1);

Getting the pow(2,11):

return 1<<11;

See also

You can leave a response, or trackback from your own site.

Leave a Reply