• Martin Thoma
  • Home
  • Categories
  • Tags
  • Archives
  • Support me

How do Bitmasks work?

Contents

  • How do Bitmasks work?
    • What are Bitmasks?
    • Bit operators
    • Some examples
    • See also

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 &amp; 1;

Get the first bit:

return variable >> 31;

Get the bits 4 - 14 (11 bits):

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

Getting the pow(2,11):

return 1<<11;

See also

  • What does a type followed by _t (underscore-t) represent?. Jonathan Leffler, Stackoverflow.
  • Why does mode_t use 4 byte?. Niklas B., Stackoverflow.

Published

Mai 18, 2012
by Martin Thoma

Category

Code

Tags

  • C 23
  • Operating Systems 5
  • OS 5

Contact

  • Martin Thoma - A blog about Code, the Web and Cyberculture
  • E-mail subscription
  • RSS-Feed
  • Privacy/Datenschutzerklärung
  • Impressum
  • Powered by Pelican. Theme: Elegant by Talha Mansoor