Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Mask (computing)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
{{Short description|Data used for bitwise operations}} {{Redirect|Signal masking||Masking (disambiguation)}}{{one source|date=April 2020}} In [[computer science]], a '''mask''' or '''bitmask''' is data that is used for [[bitwise operation]]s, particularly in a [[bit field]]. Using a mask, multiple bits in a [[byte]], [[nibble]], [[Word (computer architecture)|word]], 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 (computer architecture)|predication]] in [[vector processing]], 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 <code>1</code>=== To turn certain bits on, the [[Logical disjunction|bitwise <code>OR</code>]] operation can be used, following [[Logical disjunction#Bitwise operation|the principle]] that for an individual bit '''Y''', <code>Y OR 1 = 1</code> and <code>Y OR 0 = Y</code>. Therefore, to make sure a bit is on, <code>OR</code> can be used with a <code>1</code>. To leave a bit unchanged, <code>OR</code> is used with a <code>0</code>. Example: Masking ''on'' the higher [[nibble]] (bits 4, 5, 6, 7) while leaving the lower nibble (bits 0, 1, 2, 3) unchanged. '''1001'''0101 '''1010'''0101 OR '''1111'''0000 '''1111'''0000 = '''1111'''0101 '''1111'''0101 ===Masking bits to <code>0</code>=== More often in practice, bits are "masked ''off''" (or masked to <code>0</code>) than "masked ''on''" (or masked to <code>1</code>). When a bit is <code>AND</code>ed with a 0, the result is always 0, i.e. <code>Y AND 0 = 0</code>. To leave the other bits as they were originally, they can be <code>AND</code>ed with <code>1</code> as <code>Y AND 1 = Y</code> Example: Masking ''off'' the higher [[nibble]] (bits 4, 5, 6, 7) while leaving the lower nibble (bits 0, 1, 2, 3) unchanged. '''1001'''0101 '''1010'''0101 AND '''0000'''1111 '''0000'''1111 = '''0000'''0101 '''0000'''0101 ===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 <code>AND</code> is done as discussed above and the value is compared with <code>0</code>. If it is equal to <code>0</code>, 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 <code>0</code>. Example: Querying the status of the 4th bit 1001'''1'''101 1001'''0'''101 AND 0000'''1'''000 0000'''1'''000 = 0000'''1'''000 0000'''0'''000 ===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 [[Exclusive or|<code>XOR</code> (exclusive or)]] operation. <code>XOR</code> returns <code>1</code> [[if and only if]] an [[odd number]] of bits are <code>1</code>. Therefore, if two corresponding bits are <code>1</code>, the result will be a <code>0</code>, but if only one of them is <code>1</code>, the result will be <code>1</code>. Therefore inversion of the values of bits is done by <code>XOR</code>ing them with a <code>1</code>. If the original bit was <code>1</code>, it returns <code>1 XOR 1 = 0</code>. If the original bit was <code>0</code> it returns <code>0 XOR 1 = 1</code>. Also note that <code>XOR</code> masking is bit-safe, meaning that it will not affect unmasked bits because <code>Y XOR 0 = Y</code>, just like an <code>OR</code>. 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== [[File:Binary_guess_number_trick_SMIL.svg|thumb|upright|link={{filepath:binary_guess_number_trick_SMIL.svg}}|A party trick to guess a number from which cards it is printed on uses the bits of the binary representation of the number. In the SVG file, click a card to toggle it.]] === Arguments to functions === In programming languages such as [[C (language)|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]], there is a command, <code>glClear()</code> which clears the screen or other buffers. It can clear up to four buffers (the color, depth, accumulation, and [[stencil buffer]]s), so the API authors could have had it take four arguments. But then a call to it would look like <syntaxhighlight lang="c"> glClear(1,1,0,0); // This is not how glClear actually works and would make for unstable code.</syntaxhighlight> which is not very descriptive. Instead there are four defined field bits, <code>GL_COLOR_BUFFER_BIT</code>, <code>GL_DEPTH_BUFFER_BIT</code>, <code>GL_ACCUM_BUFFER_BIT</code>, and <code>GL_STENCIL_BUFFER_BIT</code> and <code>glClear()</code> is declared as <syntaxhighlight lang="c"> void glClear(GLbitfield bits);</syntaxhighlight> Then a call to the function looks like this <syntaxhighlight lang="c"> glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);</syntaxhighlight> Internally, a function taking a bitfield like this can use binary <code>and</code> to extract the individual bits. For example, an implementation of <code>glClear()</code> might look like: <syntaxhighlight lang="c"> void glClear(GLbitfield bits) { if ((bits & GL_COLOR_BUFFER_BIT) != 0) { // Clear color buffer. } if ((bits & GL_DEPTH_BUFFER_BIT) != 0) { // Clear depth buffer. } if ((bits & GL_ACCUM_BUFFER_BIT) != 0) { // Clear accumulation buffer. } if ((bits & GL_STENCIL_BUFFER_BIT) != 0) { // Clear stencil buffer. } }</syntaxhighlight> 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 safety|type-safe]]. A <code>GLbitfield</code> is simply defined to be an <code>unsigned int</code>, so the compiler would allow a meaningless call to <code>glClear(42)</code> or even <code>glClear(GL_POINTS)</code>. In [[C++]] 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 {{IPaddr|203.0.113.129}} with a {{IPaddr|255.255.255.224}} mask. Masks for IP ACLs are the reverse: for example, mask {{IPaddr|0.0.0.255}}. This is sometimes called an inverse mask or a [[wildcard mask]]. 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): {{IPaddr|192.0.2.0}} mask: {{IPaddr|0.0.0.255}} 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 ([[Octet (computing)|octets]]) 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 "{{IPaddr|192.0.2.}}" matches, since the last octet is "don't care". Therefore, with this mask, network addresses {{IPaddr|192.0.2.1}} through {{IPaddr|192.0.2.255}} ({{IPaddr|192.0.2.x}}) are processed. Subtract the normal mask from {{IPaddr|255.255.255.255}} in order to determine the ACL inverse mask. In this example, the inverse mask is determined for network address {{IPaddr|198.51.100.0}} with a normal mask of {{IPaddr|255.255.255.0}}. {{IPaddr|255.255.255.255}} β {{IPaddr|255.255.255.0}} (normal mask) = {{IPaddr|0.0.0.255}} (inverse mask) ACL equivalents The source/source-wildcard of {{IPaddr|0.0.0.0|255.255.255.255}} means "any". The source/wildcard of {{IPaddr|198.51.100.2|0.0.0.0}} is the same as "host {{IPaddr|198.51.100.2}}" ===Image masks=== {{see also|Bit blit|Clipping path}} [[Image:Blit dot.gif|thumb|[[Raster graphics|Raster graphic]] [[Sprite (computer graphics)|sprite]]s (left) and masks (right)]] In [[computer graphics]], when a given image is intended to be placed over a background, the transparent areas can be specified through a binary mask.<ref>{{Cite web|url=https://www.pyimagesearch.com/2018/11/19/mask-r-cnn-with-opencv/|title=Mask R-CNN with OpenCV|date=2018-11-19|website=PyImageSearch|language=en-US|access-date=2020-04-05}}</ref> This way, for each intended image there are actually two [[bitmap]]s: the actual image, in which the unused areas are given a [[pixel]] value with all [[bit]]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 (program lifecycle phase)|run time]], 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]] 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 [[Logical disjunction|bitwise OR]] 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. [[Image:Sprite rendering by binary image mask.png|center]] This technique is used for painting pointing device cursors, in typical 2-D videogames for characters, bullets and so on (the [[Sprite (computer graphics)|sprite]]s), for [[GUI]] [[Icon (computing)|icon]]s, and for video titling and other image mixing applications. A faster method is to simply overwrite the background pixels with the foreground pixels if their alpha=1 Although related (due to being used for the same purposes), [[Palette (computing)#Transparent color in palettes|transparent color]]s and [[alpha channel]]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]], 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: <syntaxhighlight lang="c"> #include <stdint.h> #include <string.h> int main(void) { const uint32_t NUM_BUCKETS = 0xFFFFFFFF; // 2^32 - 1 const uint32_t MAX_RECORDS = 1<<10; // 2^10 const uint32_t HASH_BITMASK = 0x3FF; // (2^10)-1 char **token_array = NULL; // Handle memory allocation for token_arrayβ¦ char token[] = "some hashable value"; uint32_t hashed_token = hash_function(token, strlen(token), NUM_BUCKETS); // Using modulo size_t index = hashed_token % MAX_RECORDS; // OR // Using bitmask size_t index = hashed_token & HASH_BITMASK; *(token_array+index) = token; // Free the memory from token_array β¦ return 0; } </syntaxhighlight> ==See also== *[[Affinity mask]] *[[Binary-coded decimal]] *[[Bit field]] *[[Bit manipulation]] *[[Bitwise operation]] *[[Subnet]] *[[Tagged pointer]] *[[umask]] == References == {{Reflist}} [[Category:Binary arithmetic]] [[Category:Articles with example C code]]
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)
Pages transcluded onto the current version of this page
(
help
)
:
Template:Cite web
(
edit
)
Template:IPaddr
(
edit
)
Template:One source
(
edit
)
Template:Redirect
(
edit
)
Template:Reflist
(
edit
)
Template:See also
(
edit
)
Template:Short description
(
edit
)