ProgrammingHard
Which bit trick isolates the lowest set bit of an unsigned n?
- A. n & (n - 1)
- B. n & (~n + 1), which equals n & -n for unsigned n
- C. (n << 1) | n
- D. n ^ (n * 2)
Correct answer: B. n & (~n + 1), which equals n & -n for unsigned n
n & -n keeps only the lowest set bit. n & (n - 1) clears that bit instead, which is the other common trick.
More C Programming questions
- What is the parity of the number 0b1101011 (1 for odd count of set bits)?
- What is (-8) >> 1 in C if the platform uses arithmetic right shift for signed values?
- To multiply x by 2^k where x is an unsigned 32-bit value, which code is correct?
- A program uses a modulus of 10^9 + 7 and computes (a - b + MOD) % MOD for a and b in [0, MOD). Why add MOD before the %?
- What is the value of 5 & 6 | 3 in C?
- What is the value of 0x80 | 0x01 | 0x10 in decimal?