What is the best way to construct a bit mask in C with m
set bits preceded by k
unset bits, and followed by n
unset bits:
00..0 11..1 00..0 k m n
For example, k=1, m=4, n=3 would result in the bit mask:
01111000
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.
To represent a set of N items we need a sequence of N bits where every bit represents an item in the Set. This sequence of bits used to represent a subset of a set is usually referred to as a mask. For example, the sequence of bits 10101 is a mask used to represent a set of size 5.
In Bitmasking, the idea is to visualize a number in the form of its binary representation. Some bits are “set” and some are “unset” , “set” means its value is 1 and “unset” means its value is 0. A “Bitmask” is simply a binary number that represents something.
~(~0 << m) << n
So, you are asking for m set bits prefixed by k reset bits and followed by n reset bits? We can ignore k since it will largely be constrained by the choice of integer type.
mask = ((1 << m) - 1) << n;
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