Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

In this pedagogical noncompliant code example, the flipbits() function complements the value stored in x by performing a bitwise exclusive OR against a mask with all bits set to 1. For implementations where unsigned long is represented by a 32 bit value, each bit of x is correctly complemented.

Code Block
bgColor#FFCCCC
langc
// (Incorrect) Set all bits in mask to one.
const unsigned long mask = 0xFFFFFFFF;

unsigned long flipbits(unsigned long x) {
  return x ^ mask;
}

...

Values stored in unsigned bit-fields and objects of type unsigned char shall be represented using a pure binary notation.

Code Block
bgColor#CCCCFF
langc
// (Correct) Set all bits in mask to one.
const unsigned long mask = -1;

unsigned long flipbits(unsigned long x) {
  return x ^ mask;
}

...

In this noncompliant code example, a programmer is attempting to set the most significant bit.

Code Block
bgColor#FFCCCC
langc
const unsigned long mask = 0x80000000;
unsigned long x;

/* Initialize x */

x = (x ^ mask) + 1;

...

A portable (and safer) way of setting the high order bit is to use a shift expression as in this compliant solution.

Code Block
bgColor#CCCCFF
langc
const unsigned long mask = (1 << ((sizeof(unsigned long) * CHAR_BIT) - 1))
unsigned long x;

/* Initialize x */

x = (x ^ mask) + 1;

...