3 ms·
int inc(int a) { int mask = ~a; /* Assuming a is 32-bit. If 64-bit, add 32-bit shift. */ mask |= mask << 1; mask |= mask << 2; mask |= mask
by alexl1988 15y ago
int inc(int a) {
int mask = ~a;
/* Assuming a is 32-bit. If 64-bit, add 32-bit shift. */
mask |= mask << 1;
mask |= mask << 2;
mask |= mask << 4;
mask |= mask << 8;
mask |= mask << 16;
/* Take the longest run of 1s from the right of a.
* mask has 0s there and 1s everywhere else. We want
* to set the next bit to 1 and set the ones after
* to 0. */
return (a | ~(mask << 1)) & mask;
}