News for hackers. Stuff that matters.
Re:Calculate n + 1 without using + or - or * or / by alexl1988 on Saturday July 02, 2011 @04:20AM (#2721298)

  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;
  }

There are no comments on this comment yet.