Library contents

C++ std::ldexp

Scale a binary floating-point reading by an integer power of two.

A simple example

std::ldexp

  1. Start with 3 and exponent 2
  2. Do this Multiply by 2 squared
  3. Result 12
Scaling by a power of two multiplies 3 by 4.
lesson.cpp
#include <iostream>
#include <cmath>

int main() {
    std::cout << (std::ldexp(3.0, 2)) << '\n';
}
Output
12

Syntax

C++ syntax
std::ldexp(reading, shift)
Run these examples in C++

Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.

c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson

Undo a power-of-two sensor scale

A sensor stores readings in a binary floating-point format with limited precision. Inspect or adjust the scale of the sample value so the calibration code can account for representable steps.

From the programconst double reading = 1.5
Result12.000
lesson.cpp
#include <cmath>
#include <cstdio>

int main() {
    const double reading = 1.5;
    const int shift = 3;

    std::printf("%.3f\n", std::ldexp(reading, shift));
    return 0;
}
Output
12.000

The stored reading 1.5 multiplied by two cubed becomes 12.

Advertisements

Decode the light meter’s gain

A sensor saved a reading of six with a binary exponent of two. The display restores the reading by scaling by two to that power.

Given6 · 2
Worked result24

Using 6 · 2 gives 24 for this measurement.

Reduce the image preview scale

A drawing tool stores the width 32 with a binary scale multiplier of one half. The preview uses exponent minus one to recover its width.

Given32 · -1
Worked result16

Using 32 · -1 gives 16 for this measurement.

What to watch for

The exponent is a count of binary shifts. Large shifts can overflow the result.

Documentation for std::ldexp