Can someone please explain this function to me?
A mask with the least significant n bits set to 1.
Ex:
n = 6 --> 0x2F, n = 17 --> 0x1FFFF // I don't get these at all, especially how n = 6 --> 0x2F
Also, what is a mask?
To be sure you get the right bit/value: The value at the least significant bit position = x & 1. The value of the isolated least significant 1 = x & -x. The zero-based index of the isolated least significant 1 = log2(x & -x)
Bit masking is simply the process of storing data truly as bits, as opposed to storing it as chars/ints/floats. It is incredibly useful for storing certain types of data compactly and efficiently. The idea for bit masking is based on boolean logic.
A subnet mask provides IP, routing protocol, and any other software that deals with addresses a way to determine the network ID and host ID. A subnet mask, like an IP address, is 32 bits in length.
In this tutorial, we will learn Bit masking in C++ with a program. What is a bitmask? We are well aware of the bitwise operators in C++. They are – bitwise and, or, not and exclusive or operators. We use bitmask operations to turn a bit on from off or vice-versa, check if a bit is on or off and for toggling a bit.
In the case of an & mask, a binary 0 in the mask means "unconditionally set the result bit to 0" and a 1 means "set the result bit to the input value bit".
The usual way is to take a 1, and shift it left n bits. That will give you something like: 00100000. Then subtract one from that, which will clear the bit that's set, and set all the less significant bits, so in this case we'd get: 00011111. A mask is normally used with bitwise operations, especially and.
We’ve already seen an example of masking when we used the ^ (bitwise XOR) to invert bits 0 through 15 of myValueA. Let’s suppose that the only part of myValueA in which we are interested encompasses bits 16 through 23, and we wish to clear the remaining bits to 0.
The usual way is to take a 1
, and shift it left n
bits. That will give you something like: 00100000
. Then subtract one from that, which will clear the bit that's set, and set all the less significant bits, so in this case we'd get: 00011111
.
A mask is normally used with bitwise operations, especially and
. You'd use the mask above to get the 5 least significant bits by themselves, isolated from anything else that might be present. This is especially common when dealing with hardware that will often have a single hardware register containing bits representing a number of entirely separate, unrelated quantities and/or flags.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With