Interview Questions

Why do people use explicit masks and bit-twiddling code so much?

C Interview Questions and Answers


(Continued from previous question...)

Why do people use explicit masks and bit-twiddling code so much?

Q: Why do people use explicit masks and bit-twiddling code so much, instead of declaring bit-fields?

A: Bit-fields are thought to be nonportable, although they are no less portable than other parts of the language. (You don't know how big they can be, but that's equally true for values of type int. You don't know by default whether they're signed, but that's equally true of type char. You don't know whether they're laid out from left to right or right to left in memory, but that's equally true of the bytes of all types, and only matters if you're trying to conform to externally-imposed storage layouts, which is always nonportable;

Bit-fields are inconvenient when you also want to be able to manipulate some collection of bits as a whole (perhaps to copy a set of flags). You can't have arrays of bit-fields;. Many programmers suspect that the compiler won't generate good code for bit-fields (historically, this was sometimes true).

Straightforward code using bit-fields is certainly clearer than the equivalent explicit masking instructions; it's too bad that bit-fields can't be used more often.

(Continued on next question...)

Other Interview Questions