Show how to use bit masking to check whether bits 2 and bit 5 in a byte are both on.
Show how to use bit masking to check whether bits 2 and bit 5 in a byte are both on.
Bit Masking:
Bit Masking is used to access specific bits in the data. It used to toggle bits on or off and manipulate specific bits. A bit mask prevents the bitwise operators from modifying the bits that need not be modified but allows access to the bits that needs to be modified at the same time. There are three bitwise operations used in bit masking:
- AND: It is used to check if a bit is on and off. It is denoted by bitwise AND and used by '&'. To turn off a bit '&= ~" is used.
- OR: It is used to set a bit on or off. It is denoted by bitwise OR and used by '|='.
- XOR: It is used to toggle a bit between on and off. It is denoted by bitwise XOR and used by '^='.
- Left Shift: Used to left shift a value a specified number of times. Denoted by '<<'.
- Right Shift: Used to right shift a value a specified number of times. Denoted by '>>'.
Example
In C++14 bits can be set using constexpr std::uint_fast8_t <mask_name> { 0b<8-bit mask>}.
Consexpr is used to define consyant expression and is similar to const in C++. Any changes made to a variable of constexpr will result in a compiler error. It is in library cstdint.
Mask name can be used as a variable name and 8-bit mask is set by a pair of two 4-bit numbers separated by a apostrophe (').
example: constexpr std::uint_fast8_t maskUser { 0b1111'0000}.
And user vale can also be defined in a similar manner std::uint_fast8_t value{ 0b<8-bit user defined value> }.
Trending now
This is a popular solution!
Step by step
Solved in 3 steps with 2 images