Binary and bit manipulation
Convert fast and apply the operators bit by bit.
The idea
Computers store numbers in binary. Exam questions test whether you can convert quickly, handle negative numbers and apply bitwise operators without a calculator.
Tools
- Place values. The bits of a binary number are worth 1, 2, 4, 8, 16… from the right.
- Two’s complement. To write
−ninwbits, writenin binary, flip every bit, then add 1. - Bitwise operators. AND keeps a bit only if both are 1; OR keeps it if either is 1; XOR keeps it if they differ.
- Shifts.
x << kmultiplies by 2k;x >> kdivides by 2k and drops the remainder.
Worked examples
1. What is −37 in 8-bit two’s complement?
37 is 00100101. Flip every bit to get 11011010, then add 1.
Answer: 11011011
2. How many 1 bits does 1234 have in binary?
1234 = 1024 + 128 + 64 + 16 + 2, which is 10011010010 in binary.
Answer: 5
3. What is (12 XOR 10) AND 7?
12 = 1100 and 10 = 1010. XOR gives 0110 = 6. Then 6 AND 7 = 0110 AND 0111.
Answer: 6
Common mistakes
- Forgetting the +1 in two’s complement.
- Mixing up XOR with OR (XOR of two 1s is 0).
- Losing track of the bit width when a question says “8-bit”.
Practise this topic
Try questions on this topic with instant explanations, or test yourself against the world in the ranked exam.