Whetstone
0day streak

Number Systems & Bitwise Operations

Binary, hex, two's complement, and the bit-twiddling idioms that show up in every protocol header.

7

Questions

4/2/1

Easy / Med / Hard

Your accuracy

Everything a processor does is binary underneath; hex exists purely so humans can read it without going cross-eyed. One hex digit is exactly four bits, so a byte is always two hex digits -- 0xFF is 11111111, 0x0A is 00001010 -- which is the whole reason hex is used instead of decimal for anything close to hardware.

Two's complement is how signed integers actually work. To negate a number, invert every bit and add one. The top bit acts as a sign bit, but not by simply meaning "negative" -- the representation is chosen so that ordinary binary addition produces correct results for both positive and negative numbers without the hardware needing separate logic. It's also why a signed integer's range is asymmetric: an 8-bit signed value runs from -128 to 127, not -127 to 127, because zero only needs one representation.

Bitwise operators are how you manipulate flags and fields packed into a single word, which is the normal way protocol headers, hardware registers, and permission bits are laid out. & (AND) tests or clears bits: x & mask keeps only the bits set in mask. | (OR) sets bits: x | (1 << 3) sets bit 3 without touching the rest. ^ (XOR) toggles bits and is the classic in-place swap trick. ~ inverts every bit. << and >> shift bits left or right, which for unsigned values is also a fast multiply or divide by a power of two -- but right-shifting a signed negative value is implementation-defined behaviour in older C standards depending on whether the shift is arithmetic (sign-extending) or logical (zero-filling), which is exactly the kind of thing that bites someone porting code between compilers.

The idiom worth having cold: x & (x - 1) clears the lowest set bit, which is how you check if a number is a power of two (x & (x-1) == 0) or count set bits without a lookup table. x & -x isolates the lowest set bit on its own. These show up constantly in flag-checking code and in interview questions about bit manipulation specifically because they compress a loop into one instruction.