In most programming languages, when you want to create a bitmask you usually use an integer type and bitwise operations (and, or, xor, not, shift left, shift right .. .). However, although nothing prevents the programmer from assigning a specific value (say, 6
: 110
) to the mask, constants are usually created to represent each bit and insisted - as good practice, and to avoid incompatibility problems in the future - in using these constants, avoiding the "magic values". This is not usually enforced, however.
Would there be any harm in creating an abstract "bitmask" type, whose subtypes were particular applications of this technique, and make the compiler force its use ? For example, some languages that support enums (enums) - such as Java - allow you to create methods whose parameters must be of this type, so that the programmer has no choice but to use his even when each of them has one or more associated [unique] values. And an enumeration may or may not be used to implement bit masks, but it also has other purposes [1].
My question is specifically: is there any use case for bitmasks in which the freedom to use integers instead of the defined constants brings a significant advantage, and its loss can compromise the expressiveness of the code? I think this is something that only those who have experience working with bit masks can answer, but if anyone has any external reference dealing with the subject would also be very useful. In my limited experience, the main cases of using a bitmask are:- Set multiple bits or only one particular bit (or clear a particular bit);
- Check whether a particular bit (or set of bits) is set or not;
- Serialize / deserialize (i.e. save the data structure containing the bit mask to a file or other binary / textual format).
I can not think of any other.
[1]: By the way, contrary to the premise of this related question , I have good reason to want to change the bit mask over the evolution of the products, both their individual values as their set of elements - but always versioning, so as not to break old code. This restricts my particular case, but does not invalidate the question (as I remain interested in knowing what is lost when using a bitmask type rather than a generic integer) / p>