Bitwise operators in C: solved exercise
Bitwise operators in C: solved exercise
If you searched for a solved bitwise operators exercise in C, here are all six binary operators applied to concrete values so you can see exactly which bit is set or cleared by each operation.
Bitwise operators work on the binary representation of integers and are essential in embedded systems, network protocols, configuration flags, and hardware register manipulation.
Problem statement
Given a = 12 (binary 1100) and b = 10 (binary 1010), compute and print the result of &, |, ^, ~a, a << 1, and a >> 1, also showing the hexadecimal representation where relevant.
C solution
Expected output
Common mistakes
- Confusing
&(bitwise AND) with&&(logical AND): they are completely different operators. - Applying
~to a signedintand getting unexpected negative results; useunsignedfor bitwise manipulation. - Shifting more bits than the type holds (
a << 32on a 32-bitunsigned intis undefined behavior). - Omitting parentheses around bitwise expressions in complex expressions:
&,|, and^have lower precedence than comparison operators.
Practical use
Bitwise operators are used to set, clear, or test individual flags in a bit field, mask parts of a byte in network protocols, and efficiently multiply or divide by powers of two using shifts.
Recommended next exercise
- Data types in C: solved exercise
- sizeof in C: solved exercise
- Relational and logical operators in C
- All C exercises
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
What is the difference between & and && in C?
& is the bitwise AND operator: it compares each bit of both operands. && is the logical AND operator: it evaluates whether both operands are non-zero and returns 0 or 1. They are completely different.
Why does ~12 give 4294967283 instead of -13?
~a flips all bits. On a 32-bit unsigned int, ~12 is 0xFFFFFFF3 = 4294967283. With a signed int the result is -13 (two’s complement), which is the same bit pattern interpreted differently.
When should I use shifts instead of multiply or divide?
x << 1 equals x * 2 and x >> 1 equals x / 2 for non-negative unsigned integers. Modern compilers optimize this automatically, so use shifts when the code genuinely represents bit manipulation, not as a speed trick.