Shift binary numbers left or right by any number of positions
Try an example:
Tip: A left shift by 1 multiplies the value by 2. A right shift by 1 divides by 2 (floor for unsigned, rounding toward negative infinity for signed in arithmetic mode).
Bit shifting is exactly what it sounds like: you take a binary number and slide all its bits a certain number of positions to the left or the right. Every bit moves in unison — nothing changes order, just position. When bits shift past the boundary, they're gone. The new empty positions get filled according to the shift mode.
The neat thing is what happens to the numeric value. A left shift by n positions multiplies the number by 2n. A right shift by n divides by 2n. This is why bit shifting shows up everywhere in low-level code — it's the cheapest possible multiply and divide. On most CPUs, a bit shift instruction executes in a single clock cycle, whereas a general multiply can take several cycles. When you're writing performance-critical code like video encoders or audio decoders, replacing a multiply by 4 with a shift left by 2 is a free win.
Logical shift (sometimes called unsigned shift) always fills the new empty positions with zeros. It treats the binary number as an unsigned value with no sign bit. If you shift left, the vacated LSB positions get zeros. Shift right, the vacated MSB positions get zeros. The bits that fall off the end are simply discarded. This is the simpler of the two and the one you'll use most of the time for bit-field manipulation.
Arithmetic shift preserves the sign bit (the most significant bit) during a right shift. The idea is to keep signed numbers consistent: a negative number shifted right should stay negative. When you arithmetic-shift right, the MSB (sign bit) is copied into each new position rather than zeroed. This is called sign extension. On a CPU, the SAR (Shift Arithmetic Right) instruction does this automatically. Without sign extension, shifting a negative signed number right would turn it into a large positive number, which breaks arithmetic.
Left shifts in both modes behave identically — the LSB positions fill with zeros. The difference only matters for right shifts.
flags |= (1 << 5) sets bit 5. flags & (1 << 5) checks it. Game engines, OS kernel data structures, and network protocol headers use this pattern everywhere because packing 32 flags into a single 32-bit integer is far more cache-friendly than an array of 32 booleans.(color >> 16) & 0xFF, green with (color >> 8) & 0xFF, blue with color & 0xFF. The shift moves the desired byte down to the lowest 8 bits so the mask picks it up.| Expression | Binary | Decimal |
|---|---|---|
1 << 0 |
1 | 1 |
1 << 1 |
10 | 2 |
1 << 2 |
100 | 4 |
1 << 3 |
1000 | 8 |
1 << 4 |
10000 | 16 |
1 << 5 |
100000 | 32 |
1 << 6 |
1000000 | 64 |
1 << 7 |
10000000 | 128 |