...
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 | ||||
|---|---|---|---|---|
| ||||
// (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 charshall be represented using a pure binary notation.
| Code Block | ||||
|---|---|---|---|---|
| ||||
// (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 | ||||
|---|---|---|---|---|
| ||||
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 | ||||
|---|---|---|---|---|
| ||||
const unsigned long mask = (1 << ((sizeof(unsigned long) * CHAR_BIT) - 1)) unsigned long x; /* Initialize x */ x = (x ^ mask) + 1; |
...