What is the value of 5 & 3?
5 is 101 and 3 is 011. AND keeps a 1 only where both have one: 001 = 1. (5 | 3 would be 7 and 5 ^ 3 would be 6.)
Bitwise Operators · Exercise 1 of 4
Twelve multiple-choice questions on the bitwise operators, masks, shifts and their undefined cases, precedence, integer promotion and C23 literals. Pick an option to check your answer instantly.
What is the value of 5 & 3?
5 is 101 and 3 is 011. AND keeps a 1 only where both have one: 001 = 1. (5 | 3 would be 7 and 5 ^ 3 would be 6.)
For any integer x, what is x ^ x?
XOR gives 1 only where the bits differ, and a number never differs from itself. This "cancelling" property is behind the find-the-single-number trick and simple checksums.
Which expression is 1 when bit k of an unsigned x is set, and 0 otherwise?
Shifting right by k brings bit k to position 0, and & 1u keeps only that bit. x & (1u << k) also works as a true/false test, but gives the bit's value (such as 8), not 1.
Which statement clears bit k of x and leaves every other bit unchanged?
~(1u << k) has a 0 at bit k and 1 everywhere else, so AND-ing keeps all other bits and forces bit k to 0. XOR would toggle it, OR would set it, and the last option would clear every other bit.
When is x << 1 equal to x * 2?
Shifting left by 1 doubles the value as long as no 1 bit is pushed out (unsigned arithmetic wraps the same way for both). Left-shifting a negative signed value is undefined behaviour, so the two are not the same for negatives.
For a 32-bit unsigned x, what is x << 32?
Shifting by a count greater than or equal to the width of the type is undefined, even for unsigned values. On x86 the hardware uses the count modulo 32, so it often "returns x" – but the compiler may assume it never happens.
What does the C standard say about -16 >> 2?
Right-shifting a negative value is implementation-defined. Mainstream compilers do an arithmetic shift that copies the sign bit, giving −4. Code that needs portable results should shift unsigned values.
What is -1 << 1 according to the C standard?
Left-shifting a negative signed value is undefined behaviour in C (most machines would produce −2, but optimisers may rely on it never happening). Work with unsigned values for bit patterns.
How does C parse x & 1 == 0?
== has higher precedence than &, so the expression is x & 0, which is always 0. This historical quirk is why compilers warn; always bracket bitwise expressions in comparisons.
What is the value of ~0u on a system with 32-bit unsigned int?
0u is all zero bits; ~ flips all 32 of them to 1, which is the largest unsigned value, 4294967295. ~0 (signed) is −1, the same bits read as a signed int.
Timed online tests with instant scores and explanations.