In
computer science
Computer science is the study of computation, automation, and information. Computer science spans theoretical disciplines (such as algorithms, theory of computation, information theory, and automation) to Applied science, practical discipli ...
, a mask or bitmask is data that is used for
bitwise operation
In computer programming, a bitwise operation operates on a bit string, a bit array or a binary numeral (considered as a bit string) at the level of its individual bits. It is a fast and simple action, basic to the higher-level arithmetic operati ...
s, particularly in a
bit field
A bit field is a data structure that consists of one or more adjacent bits which have been allocated for specific purposes, so that any single bit or group of bits within the structure can be set or inspected. A bit field is most commonly used to r ...
. Using a mask, multiple bits in a
byte
The byte is a unit of digital information that most commonly consists of eight bits. Historically, the byte was the number of bits used to encode a single character of text in a computer and for this reason it is the smallest addressable unit ...
,
nibble
In computing, a nibble (occasionally nybble, nyble, or nybl to match the spelling of byte) is a four-bit aggregation, or half an octet. It is also known as half-byte or tetrade. In a networking or telecommunication context, the nibble is oft ...
,
word
A word is a basic element of language that carries an semantics, objective or pragmatics, practical semantics, meaning, can be used on its own, and is uninterruptible. Despite the fact that language speakers often have an intuitive grasp of w ...
, etc. can be set either on or off, or inverted from on to off (or vice versa) in a single bitwise operation. An additional use of masking involves
predication in
vector processing
In computing, a vector processor or array processor is a central processing unit (CPU) that implements an instruction set where its instructions are designed to operate efficiently and effectively on large one-dimensional arrays of data called ' ...
, where the bitmask is used to select which element operations in the vector are to be executed (mask bit is enabled) and which are not (mask bit is clear).
Common bitmask functions
Masking bits to 1
To turn certain bits on, the
bitwise OR
operation can be used, following
the principle
''The Principle'' is a 2014 American independent film produced by Rick DeLano and Robert Sungenis. It rejects the Copernican principle and supports the long-superseded notion and pseudoscientific principle that Earth is at the center of the ...
that
Y OR 1 = 1
and
Y OR 0 = Y
. Therefore, to make sure a bit is on,
OR
can be used with a
1
. To leave a bit unchanged,
OR
is used with a
0
.
Example: Masking ''on'' the higher
nibble
In computing, a nibble (occasionally nybble, nyble, or nybl to match the spelling of byte) is a four-bit aggregation, or half an octet. It is also known as half-byte or tetrade. In a networking or telecommunication context, the nibble is oft ...
(bits 4, 5, 6, 7) while leaving the lower nibble (bits 0, 1, 2, 3) unchanged.
10010101 10100101
OR 11110000 11110000
= 11110101 11110101
Masking bits to 0
More often in practice, bits are "masked ''off''" (or masked to
0
) than "masked ''on''" (or masked to
1
). When a bit is
AND
ed with a 0, the result is always 0, i.e.
Y AND 0 = 0
. To leave the other bits as they were originally, they can be
AND
ed with
1
as
Y AND 1 = Y
Example: Masking ''off'' the higher
nibble
In computing, a nibble (occasionally nybble, nyble, or nybl to match the spelling of byte) is a four-bit aggregation, or half an octet. It is also known as half-byte or tetrade. In a networking or telecommunication context, the nibble is oft ...
(bits 4, 5, 6, 7) while leaving the lower nibble (bits 0, 1, 2, 3) unchanged.
10010101 10100101
AND 00001111 00001111
= 00000101 00000101
Querying the status of a bit
It is possible to use bitmasks to easily check the state of individual bits regardless of the other bits. To do this, turning off all the other bits using the bitwise
AND
is done as discussed
above and the value is compared with
0
. If it is equal to
0
, then the bit was off, but if the value is any other value, then the bit was on. What makes this convenient is that it is not necessary to figure out what the value actually is, just that it is not
0
.
Example: Querying the status of the 4th bit
10011101 10010101
AND 00001000 00001000
= 00001000 00000000
Toggling bit values
So far the article has covered how to turn bits on and turn bits off, but not both at once. Sometimes it does not really matter what the value is, but it must be made the opposite of what it currently is. This can be achieved using the
XOR
(exclusive or) operation.
XOR
returns
1
if and only if
In logic and related fields such as mathematics and philosophy, "if and only if" (shortened as "iff") is a biconditional logical connective between statements, where either both statements are true or both are false.
The connective is bicondi ...
an
odd number
In mathematics, parity is the property of an integer of whether it is even or odd. An integer is even if it is a multiple of two, and odd if it is not.. For example, −4, 0, 82 are even because
\begin
-2 \cdot 2 &= -4 \\
0 \cdot 2 &= 0 \\
41 ...
of bits are
1
. Therefore, if two corresponding bits are
1
, the result will be a
0
, but if only one of them is
1
, the result will be
1
. Therefore inversion of the values of bits is done by
XOR
ing them with a
1
. If the original bit was
1
, it returns
1 XOR 1 = 0
. If the original bit was
0
it returns
0 XOR 1 = 1
. Also note that
XOR
masking is bit-safe, meaning that it will not affect unmasked bits because
Y XOR 0 = Y
, just like an
OR
.
Example: Toggling bit values
10011101 10010101
XOR 00001111 11111111
= 10010010 01101010
To write arbitrary 1s and 0s to a subset of bits, first write 0s to that subset, then set the high bits:
register = (register & ~bitmask) , value;
Uses of bitmasks
Arguments to functions
In programming languages such as
C, bit fields are a useful way to pass a set of named boolean arguments to a function. For example, in the graphics API
OpenGL
OpenGL (Open Graphics Library) is a cross-language, cross-platform application programming interface (API) for rendering 2D and 3D vector graphics. The API is typically used to interact with a graphics processing unit (GPU), to achieve hardwa ...
, there is a command,
glClear()
which clears the screen or other buffers. It can clear up to four buffers (the color, depth, accumulation, and
stencil buffer
A stencil buffer is an extra data buffer, in addition to the ''color buffer'' and ''Z-buffer'', found on modern graphics hardware. The buffer is per pixel and works on integer values, usually with a depth of one byte per pixel. The Z-buffer and ...
s), so the API authors could have had it take four arguments. But then a call to it would look like
glClear(1,1,0,0); // This is not how glClear actually works and would make for unstable code.
which is not very descriptive. Instead there are four defined field bits,
GL_COLOR_BUFFER_BIT
,
GL_DEPTH_BUFFER_BIT
,
GL_ACCUM_BUFFER_BIT
, and
GL_STENCIL_BUFFER_BIT
and
glClear()
is declared as
void glClear(GLbitfield bits);
Then a call to the function looks like this
glClear(GL_COLOR_BUFFER_BIT , GL_DEPTH_BUFFER_BIT);
Internally, a function taking a bitfield like this can use binary
and
to extract the individual bits. For example, an implementation of
glClear()
might look like:
void glClear(GLbitfield bits)
The advantage to this approach is that function argument overhead is decreased. Since the minimum datum size is one byte, separating the options into separate arguments would be wasting seven bits per argument and would occupy more stack space. Instead, functions typically accept one or more 32-bit integers, with up to 32 option bits in each. While elegant, in the simplest implementation this solution is not
type-safe
In computer science, type safety and type soundness are the extent to which a programming language discourages or prevents type errors. Type safety is sometimes alternatively considered to be a property of facilities of a computer language; that is ...
. A
GLbitfield
is simply defined to be an
unsigned int
, so the compiler would allow a meaningless call to
glClear(42)
or even
glClear(GL_POINTS)
. In
C++
C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
an alternative would be to create a class to encapsulate the set of arguments that glClear could accept and could be cleanly encapsulated in a library.
Inverse masks
Masks are used with IP addresses in IP ACLs (Access Control Lists) to specify what should be permitted and denied. To configure IP addresses on interfaces, masks start with 255 and have the large values on the left side: for example, IP address with a mask. Masks for IP ACLs are the reverse: for example, mask . This is sometimes called an inverse mask or a
wildcard mask
A wildcard mask is a mask of bits that indicates which parts of an IP address are available for examination. In the Cisco IOS, . When the value of the mask is broken down into binary (0s and 1s), the results determine which address bits are to be considered in processing the traffic. A ''0''-bit indicates that the address bit must be considered (exact match); a ''1''-bit in the mask is a "don't care". This table further explains the concept.
Mask example:
network address (traffic that is to be processed):
mask:
network address (binary): 11000000.00000000.00000010.00000000
mask (binary): 00000000.00000000.00000000.11111111
Based on the binary mask, it can be seen that the first three sets (
octets
Octet may refer to:
Music
* Octet (music), ensemble consisting of eight instruments or voices, or composition written for such an ensemble
** String octet, a piece of music written for eight string instruments
*** Octet (Mendelssohn), 1825 compos ...
) must match the given binary network address exactly (11000000.00000000.00000010). The last set of numbers is made of "don't cares" (.11111111). Therefore, all traffic that begins with "" matches, since the last octet is "don't care". Therefore, with this mask, network addresses through () are processed.
Subtract the normal mask from in order to determine the ACL inverse mask. In this example, the inverse mask is determined for network address with a normal mask of .
- (normal mask) = (inverse mask)
ACL equivalents
The source/source-wildcard of means "any".
The source/wildcard of is the same as "host "
Image masks
In
computer graphics
Computer graphics deals with generating images with the aid of computers. Today, computer graphics is a core technology in digital photography, film, video games, cell phone and computer displays, and many specialized applications. A great de ...
, when a given image is intended to be placed over a background, the transparent areas can be specified through a binary mask.
This way, for each intended image there are actually two
bitmap
In computing, a bitmap is a mapping from some domain (for example, a range of integers) to bits. It is also called a bit array
A bit array (also known as bitmask, bit map, bit set, bit string, or bit vector) is an array data structure that c ...
s: the actual image, in which the unused areas are given a
pixel
In digital imaging, a pixel (abbreviated px), pel, or picture element is the smallest addressable element in a raster image, or the smallest point in an all points addressable display device.
In most digital display devices, pixels are the smal ...
value with all
bit
The bit is the most basic unit of information in computing and digital communications. The name is a portmanteau of binary digit. The bit represents a logical state with one of two possible values. These values are most commonly represente ...
s set to 0s, and an additional ''mask'', in which the correspondent image areas are given a pixel value of all bits set to 0s and the surrounding areas a value of all bits set to 1s. In the sample at right, black pixels have the all-zero bits and white pixels have the all-one bits.
At
run time
Run(s) or RUN may refer to:
Places
* Run (island), one of the Banda Islands in Indonesia
* Run (stream), a stream in the Dutch province of North Brabant
People
* Run (rapper), Joseph Simmons, now known as "Reverend Run", from the hip-hop group ...
, to put the image on the screen over the background, the program first masks the screen pixel's bits with the image mask at the desired coordinates using the
bitwise AND
In computer programming, a bitwise operation operates on a bit string, a bit array or a binary numeral (considered as a bit string) at the level of its individual bits. It is a fast and simple action, basic to the higher-level arithmetic operati ...
operation. This preserves the background pixels of the transparent areas while resets with zeros the bits of the pixels which will be obscured by the overlapped image.
Then, the program renders the image pixel's bits by combining them with the background pixel's bits using the
bitwise OR
In computer programming, a bitwise operation operates on a bit string, a bit array or a binary numeral (considered as a bit string) at the level of its individual bits. It is a fast and simple action, basic to the higher-level arithmetic operati ...
operation. This way, the image pixels are appropriately placed while keeping the background surrounding pixels preserved. The result is a perfect compound of the image over the background.
This technique is used for painting pointing device cursors, in typical 2-D videogames for characters, bullets and so on (the
sprites), for
GUI
The GUI ( "UI" by itself is still usually pronounced . or ), graphical user interface, is a form of user interface that allows users to interact with electronic devices through graphical icons and audio indicator such as primary notation, inste ...
icon
An icon () is a religious work of art, most commonly a painting, in the cultures of the Eastern Orthodox, Oriental Orthodox, and Catholic churches. They are not simply artworks; "an icon is a sacred image used in religious devotion". The most ...
s, and for video titling and other image mixing applications.
Although related (due to being used for the same purposes),
transparent colors and
alpha channel
In computer graphics, alpha compositing or alpha blending is the process of combining one image with a background to create the appearance of partial or full transparency. It is often useful to render picture elements (pixels) in separate pas ...
s are techniques which do not involve the image pixel mixage by binary masking.
Hash tables
To create a hashing function for a
hash table
In computing, a hash table, also known as hash map, is a data structure that implements an associative array or dictionary. It is an abstract data type that maps keys to values. A hash table uses a hash function to compute an ''index'', als ...
, often a function is used that has a large domain. To create an index from the output of the function, a modulo can be taken to reduce the size of the domain to match the size of the array; however, it is often faster on many processors to restrict the size of the hash table to powers of two sizes and use a bitmask instead.
An example of both modulo and masking in C:
#include
#include
int main(void)
See also
*
Affinity mask
An affinity mask is a bit mask indicating what processor(s) a thread or process should be run on by the scheduler of an operating system. Setting the affinity mask for certain processes running under Windows can be useful as there are several sy ...
*
Binary-coded decimal
In computing and electronic systems, binary-coded decimal (BCD) is a class of binary encodings of decimal numbers where each digit is represented by a fixed number of bits, usually four or eight. Sometimes, special bit patterns are used for ...
*
Bit field
A bit field is a data structure that consists of one or more adjacent bits which have been allocated for specific purposes, so that any single bit or group of bits within the structure can be set or inspected. A bit field is most commonly used to r ...
*
Bit manipulation
Bit manipulation is the act of algorithmically manipulating bits or other pieces of data shorter than a word. Computer programming tasks that require bit manipulation include low-level device control, error detection and correction algorithms, ...
*
Bitwise operation
In computer programming, a bitwise operation operates on a bit string, a bit array or a binary numeral (considered as a bit string) at the level of its individual bits. It is a fast and simple action, basic to the higher-level arithmetic operati ...
*
Subnetwork
A subnetwork or subnet is a logical subdivision of an IP network. Updated by RFC 6918. The practice of dividing a network into two or more networks is called subnetting.
Computers that belong to the same subnet are addressed with an identical ...
*
Tagged pointer In computer science, a tagged pointer is a pointer (concretely a memory address) with additional data associated with it, such as an indirection bit or reference count. This additional data is often "folded" into the pointer, meaning stored inline ...
*
umask
In computing, umask is a command (computing), command that determines the settings of a Mask (computing), mask that controls how file permissions are set for newly created files. It may also affect how the file permissions are changed explicitly. ...
References
{{Reflist
Binary arithmetic
Articles with example C code