A.1 — PRINT BINARY IN C AND JAVA
First step of debugging any bit bug: print what you actually have
Never guess at bit patterns in your head. Print them. Compare visually.A.2 — COMMON BUG CHECKLIST
| Bug | Example of the mistake | Fix |
|---|---|---|
| Missing parentheses | x & mask == 0 — parsed as x & (mask==0) |
(x & mask) == 0 |
| Sign extension on ~ | ~(uint8_t)x gives 32-bit result 0xFFFFFF00 |
(uint8_t)(~x) — cast after NOT |
| Shift by ≥ type width | 1 << 32 on int — undefined behaviour |
1ULL << 32 or use 64-bit type |
| Signed right shift | signed x >> n fills sign bit (arithmetic) |
Cast to unsigned, or use >>> in Java |
| No ntohs() before mask | Masking network-order bytes gives wrong fields on x86 | Always ntohs() / ntohl() before masking |
| Align not power of 2 | & (align-1) gives garbage if align=7 |
assert((align & (align-1)) == 0) at init |
| Ring size not pow2 | & mask wraps incorrectly |
Enforce nextPow2() at ring creation |
| Bit check vs exact match | if (x & mask) where mask has multiple bits — checks any, not all |
if ((x & mask) == mask) to require all bits set |
A.3 — OPERATOR PRECEDENCE QUICK REFERENCE (BITWISE CONTEXT)
Priority | Operator(s) | Notes -----------+----------------------+--------------------------------------- Highest | ~ | Bitwise NOT (unary) — applies first | << >> | Shifts | & | Bitwise AND | ^ | Bitwise XOR | | | Bitwise OR -----------+----------------------+--------------------------------------- !!! TRAP | == != < > <= >= | Comparisons — ABOVE & ^ | ← GOTCHA! -----------+----------------------+--------------------------------------- | && | Logical AND | || | Logical OR Lowest | = |= &= ^= <<= >>= | Assignment operators
| Expression | How it parses | What you meant |
|---|---|---|
x & 0xFF == 0 | x & (0xFF == 0) — always x & 0 | (x & 0xFF) == 0 |
a | b > 0 | a | (b > 0) — adds 0 or 1 | (a | b) > 0 |
flags & FLAG != 0 | flags & (FLAG != 0) — flags & 1 | (flags & FLAG) != 0 |
a ^ b == c | a ^ (b == c) — XOR with bool | (a ^ b) == c |
~x & mask | OK — ~ is highest bitwise | Fine as-is |
x << 2 & mask | OK — shifts before AND | Fine as-is |
MASTERY CHECKLIST — BEFORE YOU SHIP BIT CODE
- All bitwise expressions mixed with comparisons have explicit parentheses
- NOT (~) on sub-int types is followed by an explicit cast back to the target type
- Shift amounts are < the width of the type (use ULL literals for 64-bit shifts)
- Signed types use >>> (Java) or explicit cast to unsigned (C) where logical shift needed
- All multi-byte network fields are converted with ntohs()/ntohl() before masking
- Alignment values are validated to be powers of 2 at initialisation
- Ring/hash table sizes are enforced to be powers of 2 before using &mask trick
- Printed binary representation validates every intermediate mask value