Left Shift and Scaling by Powers of Two

Shifting a nonnegative binary integer left inserts lower zero bits and multiplies its value by a power of two when the result is representable.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Translate one bit pattern
  2. State the arithmetic rule
  3. Compare exact scaling with an eight-bit result
  4. State the shift model for negative inputs and large counts

Translate one bit pattern

Moving 0011 two places left gives 1100 in four bits, representing twelve. Shifting the same result once more under four-bit truncation drops a leading bit. Binary positional weights explain both the scale and the loss.

State the arithmetic rule

For Python integers, 3 << 2 is twelve without a four-bit cap. Fixed-width language rules can depend on the operand type and shift count. See bounded integer representation.[1]

Compare exact scaling with an eight-bit result

The value twenty-one is 00010101 in eight bits. Shifting left by three gives 168, which still fits. Shifting left by four gives 336 in exact arithmetic. Keeping only eight bits leaves eighty. See checking before narrowing.

21 × 2³ = 168 → 10101000
21 × 2⁴ = 336 → 1 01010000
Low eight bits in second case: 01010000 = 80

State the shift model for negative inputs and large counts

The relation to multiplication holds exactly for nonnegative integers of unrestricted precision. Fixed-width types may introduce truncation, rejection or language-specific rules. Test a shift that keeps the top bit and one that discards it.

References

  1. Python Software Foundation, Python Standard Library: Built-in Types ↩