Left/right shift
Beginner · 7 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A shift slides all the bits of a number left or right. Shifting left by one doubles the number, shifting right by one halves it. It is also the standard way to pack several small values into one number and pull them back out.
Practical use cases
- Web app: Colour picker and canvas tools. A design tool stores a colour as one number made of red, green and blue parts. To get the red amount, the code shifts right by 16 and keeps the last 8 bits. To build a colour, it shifts each part into place and joins them, which is far quicker than doing string work.
- Web app: IP address handling in admin tools. A security dashboard blocks traffic from 192.168.1.x. Each part of an IP address is one byte in a 32-bit number, so shifting splits or builds it. The page can then check whether an address falls in a blocked range with one comparison.
- System: Fast multiply and midpoints. Doubling by a left shift and halving by a right shift are the cheapest operations a processor has. Binary search code often finds the midpoint as (low plus high) shifted right by one. Compilers quietly swap a multiplication by 8 for a shift by 3, so your everyday arithmetic is already running on these tricks.
The story: The Sliding Bulbs
Grandpa Bhaskar had an old electric board with eight little bulbs in a row, which he used to show Mira how computers count. "A lit bulb on the far right is worth 1. The next is worth 2, then 4, 8, 16... each bulb is worth double the one to its right." To show 5, he lit the bulbs for 4 and 1.
"Now watch." Grandpa slid every lit bulb one place to the left. The 1 became 2 and the 4 became 8, so the total was 10. "Everything doubled, just by sliding!" Another slide gave 20. Mira clapped. No multiplication was needed at all, only moving lights.
Then he slid the lights to the right. 44 became 22: halved. But when he tried 45, the last bulb fell off the end of the board. "That is why sliding right is divide by 2 and forget the remainder."
These slides are called left shift (<<) and right shift (>>). They are among the fastest things a computer can do, and programmers use them to multiply and divide by powers of two, and to pack several small numbers into one big one.
How to spot this problem, and where you need it
You need to split a number into parts, pack several small values into one, or multiply or divide by 2 many times, and you want this to be simple and fast.
Signs you need it
- You see hex colour codes, IP addresses, or packed ids and need to read or write a single part.
- The task keeps multiplying or dividing by 2, 4, 8, or 1024, such as page sizes or byte units.
- Several small values, like a date, a status and a type, must travel in one integer.
Where to use it in a project
- Colour manipulation in canvas, image and chart code, such as lightening or extracting channels.
- Working with IP ranges, binary protocols, compact ids and packed data in APIs or files.
The solution
To read a part, shift right until the part sits at the end, then keep only its bits with AND and a mask. To write a part, shift it left to its place and join it with OR. Each shift left by one step doubles, so shifting by 3 multiplies by 8. Each shift right halves and drops the remainder.
Payoff: Before: slicing a colour from a text string with several function calls. After: two shifts and one mask give red, green and blue instantly.
Explain it like I am 8
Imagine a row of switches where each switch is worth double the one on its right. If you slide all the lit switches one step left, every one becomes worth twice as much, so the whole number doubles. Slide right and it halves.
How it works, step by step
- Write the number in binary: bulbs worth 1, 2, 4, 8, 16... from right to left.
- Left shift by k (
x << k): slide all bits k places left, fill the right with zeros. It multiplies by 2 to the power k. - Right shift by k (
x >> k): slide k places right; the lowest bits fall off. It divides by 2 to the power k, rounding down. - Use it to pack data: shift a value into its own slot (
r << 16), then OR the slots together. - Watch the size: JavaScript shifts work on 32-bit integers, so big left-shifts can wrap into negative numbers.
The code in four languages
PHP
<?php
// Left shift doubles, right shift halves (rounding down).
echo "5 << 1 = " . (5 << 1) . "
"; // 10
echo "5 << 2 = " . (5 << 2) . "
"; // 20
echo "44 >> 1 = " . (44 >> 1) . "
"; // 22
echo "45 >> 1 = " . (45 >> 1) . "
"; // 22 (the lowest bit fell off)
echo "40 >> 3 = " . (40 >> 3) . "
"; // 5
// Pack an RGB colour (three bytes) into ONE number, then unpack it.
function packRgb(int $r, int $g, int $b): int {
return ($r << 16) | ($g << 8) | $b;
}
function unpackRgb(int $c): array {
return [($c >> 16) & 255, ($c >> 8) & 255, $c & 255];
}
$orange = packRgb(255, 128, 0);
echo "orange packed = $orange (hex " . dechex($orange) . ")
"; // ff8000
echo "unpacked = " . implode(', ', unpackRgb($orange)) . "
";JavaScript
// Left shift doubles, right shift halves (rounding down).
console.log("5 << 1 = " + (5 << 1)); // 10
console.log("5 << 2 = " + (5 << 2)); // 20
console.log("44 >> 1 = " + (44 >> 1)); // 22
console.log("45 >> 1 = " + (45 >> 1)); // 22 (the lowest bit fell off)
console.log("40 >> 3 = " + (40 >> 3)); // 5
// Pack an RGB colour (three bytes) into ONE number, then unpack it.
function packRgb(r, g, b) {
return (r << 16) | (g << 8) | b;
}
function unpackRgb(c) {
return [(c >> 16) & 255, (c >> 8) & 255, c & 255];
}
const orange = packRgb(255, 128, 0);
console.log("orange packed = " + orange + " (hex " + orange.toString(16) + ")"); // ff8000
console.log("unpacked = " + unpackRgb(orange).join(', '));Java
public class Main {
// Pack an RGB colour (three bytes) into ONE number, then unpack it.
static int packRgb(int r, int g, int b) {
return (r << 16) | (g << 8) | b;
}
static int[] unpackRgb(int c) {
return new int[]{(c >> 16) & 255, (c >> 8) & 255, c & 255};
}
public static void main(String[] args) {
// Left shift doubles, right shift halves (rounding down).
System.out.println("5 << 1 = " + (5 << 1)); // 10
System.out.println("5 << 2 = " + (5 << 2)); // 20
System.out.println("44 >> 1 = " + (44 >> 1)); // 22
System.out.println("45 >> 1 = " + (45 >> 1)); // 22 (the lowest bit fell off)
System.out.println("40 >> 3 = " + (40 >> 3)); // 5
int orange = packRgb(255, 128, 0);
System.out.println("orange packed = " + orange + " (hex " + Integer.toHexString(orange) + ")"); // ff8000
int[] rgb = unpackRgb(orange);
System.out.println("unpacked = " + rgb[0] + ", " + rgb[1] + ", " + rgb[2]);
}
}Go
package main
import "fmt"
// packRgb packs an RGB colour (three bytes) into ONE number.
func packRgb(r, g, b int) int {
return (r << 16) | (g << 8) | b
}
func unpackRgb(c int) (r, g, b int) {
return (c >> 16) & 255, (c >> 8) & 255, c & 255
}
func main() {
// Left shift doubles, right shift halves (rounding down).
fmt.Println("5 << 1 =", 5<<1) // 10
fmt.Println("5 << 2 =", 5<<2) // 20
fmt.Println("44 >> 1 =", 44>>1) // 22
fmt.Println("45 >> 1 =", 45>>1) // 22 (the lowest bit fell off)
fmt.Println("40 >> 3 =", 40>>3) // 5
orange := packRgb(255, 128, 0)
fmt.Printf("orange packed = %d (hex %x)\n", orange, orange) // ff8000
r, g, b := unpackRgb(orange)
fmt.Printf("unpacked = %d, %d, %d\n", r, g, b)
}Time: O(1) · Extra space: O(1). A shift is one tiny instruction for the CPU, one of the cheapest operations available.
Watch out for
- Believing shifts work like regular decimal digits. Left shift multiplies by 2, not by 10.
- Shifting negative numbers and expecting a neat "divide by 2": the sign bit is kept, so -5 >> 1 gives -3, not -2.
- Forgetting JavaScript works on 32 bits, so
1 << 31becomes negative and1 << 32wraps back to 1.
Quick check
- What is 3 << 2?
- 6
- 9
- 12
- What is 13 >> 1?
- 6
- 7
- 6.5
- Why does a left shift by one double the number?
- Because zeros are added to the left
- Every bit moves to a place worth twice as much
- Because the CPU is fast