Note that there are some explanatory texts on larger screens.

plurals
  1. POBitfield manipulation in C
    text
    copied!<p>The classic problem of testing and setting individual bits in an integer in C is perhaps one the most common intermediate-level programming skills. You set and test with simple bitmasks such as </p> <pre><code>unsigned int mask = 1&lt;&lt;11; if (value &amp; mask) {....} // Test for the bit value |= mask; // set the bit value &amp;= ~mask; // clear the bit </code></pre> <p>An <a href="http://www.pagetable.com/?p=250" rel="noreferrer">interesting blog post</a> argues that this is error prone, difficult to maintain, and poor practice. The C language itself provides bit level access which is typesafe and portable:</p> <pre><code>typedef unsigned int boolean_t; #define FALSE 0 #define TRUE !FALSE typedef union { struct { boolean_t user:1; boolean_t zero:1; boolean_t force:1; int :28; /* unused */ boolean_t compat:1; /* bit 31 */ }; int raw; } flags_t; int create_object(flags_t flags) { boolean_t is_compat = flags.compat; if (is_compat) flags.force = FALSE; if (flags.force) { [...] } [...] } </code></pre> <p>But this makes me <strong>cringe</strong>. </p> <p>The interesting argument my coworker and I had about this is still unresolved. Both styles work, and I maintain the classic bitmask method is easy, safe, and clear. My coworker agrees it's common and easy, but the bitfield union method is worth the extra few lines to make it portable and safer.</p> <p>Is there any more arguments for either side? In particular is there some possible failure, perhaps with endianness, that the bitmask method may miss but where the structure method is safe?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload