C ldexp
Scale a binary floating-point reading by an integer power of two.
A simple example
ldexp
- Start with 3 and exponent 2
- Do this Multiply by 2 squared
- Result 12
#include <stdio.h>
#include <math.h>
int main(void) {
printf("%.15g\n", (double) (ldexp(3.0, 2)));
}
12
Syntax
ldexp(reading, shift)
Run these examples in C
Save one example at a time as lesson.c. Use C17 and a Unix-style shell.
cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lessonUndo 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.
#include <math.h>
#include <stdio.h>
int main(void) {
double reading = 1.5;
int shift = 3;
printf("%.3f\n", ldexp(reading, shift));
return 0;
}
12.000
The stored reading 1.5 multiplied by two cubed becomes 12.
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.
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.
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.