Conversion

Lesson 64: Using long() Conversion

Learn how long() conversion handles larger whole-number values for timing, counters, and math that exceed int range.

Progress indicator

Lesson 64 of 64

Learning Objectives

  • Understand what long() conversion does in Arduino.
  • Learn how long() helps with larger integer math safely.
  • Differentiate long() casting from long variable declaration.
  • Use long() in timing/counter formulas that can exceed int range.
  • Avoid overflow mistakes caused by late or missing conversion.
  • Apply long literals and casting order correctly in real embedded formulas.

Concept Explanation

What is long() Conversion

long() converts a value into long type (larger signed integer).

This is useful when values may grow beyond typical int range during math.

long() Syntax

long result = long(value);
long product = long(a) * long(b);

How long() Works

  1. Evaluate source value/expression term.
  2. Convert it to long integer representation.
  3. Perform later arithmetic with larger range protection.
  4. Store final result as long.

Critical point: if overflow happens before conversion, casting later cannot fix the wrong value. Convert risky operands first.

Type Casting Concept

Casting forces type conversion explicitly to prevent unintended overflow in intermediate math.

int a = 32760;
int b = 30000;
long safeProduct = long(a) * long(b);

Unsafe pattern: long(a * b) (if a * b overflows as int first).

long() vs long Variable

  • long value; declares variable type.
  • long(expr) converts expression value to long.
  • Combined usage: long total = long(a) * long(b);

Declaration controls storage type; casting controls how the expression is evaluated now.

When to Use long()

  • millis()/micros()-style timing math.
  • Large counters and accumulated totals.
  • Products/sums where int may overflow.
  • Converting protocol/time values to microseconds or large thresholds.

Example Code

This sketch uses long() conversion to keep large timing and multiplication results safe.

const int LED_PIN = 2;

int sensorCount = 32760;
int pulseMs = 1200;
int scaleFactor = 30000;

void setup() {
  pinMode(LED_PIN, OUTPUT);
  Serial.begin(115200);
}

void loop() {
  long totalTicks = long(sensorCount) * long(scaleFactor);
  long timeoutUs = long(pulseMs) * 1000L;
  long shifted = long(sensorCount + 50000);
  long threshold = 1000000L;

  if (totalTicks > threshold) {
    digitalWrite(LED_PIN, HIGH);
  } else {
    digitalWrite(LED_PIN, LOW);
  }

  Serial.print("totalTicks=");
  Serial.print(totalTicks);
  Serial.print(", timeoutUs=");
  Serial.print(timeoutUs);
  Serial.print(", shifted=");
  Serial.println(shifted);

  delay(900);
}

Example Code Explanation

  1. long(sensorCount) * long(scaleFactor) avoids int overflow in product.
  2. timeoutUs converts milliseconds to microseconds safely using long.
  3. shifted demonstrates larger-range addition result storage.
  4. threshold uses long literal for clear large-value comparison.
  5. LED logic checks large computed value against threshold.
  6. Serial output prints long results for runtime verification.
  7. This pattern is common in event counters and timing windows where values grow across loop cycles.

What Happens Inside

  1. Operands are promoted to long before critical arithmetic.
  2. Intermediate result keeps larger integer range.
  3. Final long values are stored and compared safely.
  4. Runtime output reflects overflow-safe calculations.
Key idea: cast early in expression, not after risky arithmetic is already done.
ExpressionResult QualityReason
long(a) * long(b)SafeMultiplication happens in long domain.
long(a * b)RiskyOverflow may happen before cast.

Common Mistakes with long()

  • Casting after overflow already happened in int expression.
  • Using plain int literals where long literal (L) is safer.
  • Assuming all boards have identical int/long sizes without checking target platform.
  • Mixing signed/unsigned long logic without clear intent.
  • Using 1000000 instead of 1000000L in large literal expressions.

Best Practices for long()

  • Cast operands before multiplication when values are large.
  • Use long literals (1000000L) for large constants.
  • Use Serial logs while validating large-range calculations.
  • Document expected max/min values in timing and counter code.
  • Use test values near limits to validate overflow safety early.

Try it now

Open the simulator workspace and inspect long() conversion values step-by-step.

Run in Simulator