C exp2() Function

Definition
In C, exp2() returns 2 raised to the power x. exp2(3) is 8, and exp2(0) is 1.
You pass one double. The result is a positive double. Include <math.h>. On GCC, link with -lm.
Syntax
Pass the exponent. Start with this call.
| Call | What it does |
|---|
exp2(3.0) | Returns 8, because 2³ = 8. |
exp2(-1.0) | Returns 0.5, because 2⁻¹ = 1/2. |
Include <math.h>. On GCC, link with -lm. Prefer exp2 over pow(2.0, x) when you specifically need powers of two.
Library declarations
double exp2(double x);
float exp2f(float x);
long double exp2l(long double x);
Parameters
| Parameter | Description |
|---|
| x | Required. The exponent for base 2. |
Return Value
| Return Value | Description |
|---|
| double | 2 to the power x. exp2(0) is 1. Negative x gives a fraction. |
C Examples
Example 1 — Basic Powers of Two
Print a few exact powers of two.
#include <stdio.h>
#include <math.h>
int main(void) {
printf("%.1f\n", exp2(0.0));
printf("%.1f\n", exp2(3.0));
printf("%.1f\n", exp2(-1.0));
return 0;
}
How It Works
- Include math.h. That declares
exp2. - Zero exponent. Any nonzero base to power 0 is 1.
- Positive exponent.
exp2(3) is 8. - Negative exponent.
exp2(-1) is 0.5.
Example 2 — Scale by a Power of Two
Multiply a sample by 2^n without writing a loop.
#include <stdio.h>
#include <math.h>
int main(void) {
double sample = 1.25;
double n = 4.0;
double scaled = sample * exp2(n);
printf("scaled = %.2f\n", scaled);
return 0;
}
How It Works
- Start with a sample. 1.25 is the base value.
- Choose n. Raise 2 to the 4th power.
- Multiply. 1.25 × 16 = 20.
- Common pattern. Bit-scale style math in floating point.
Example 3 — Fractional Exponent
exp2 also works with non-integer exponents.
#include <stdio.h>
#include <math.h>
int main(void) {
printf("%.6f\n", exp2(0.5));
printf("%.6f\n", exp2(1.5));
return 0;
}
How It Works
- Half power.
exp2(0.5) is √2 ≈ 1.414. - One and a half.
exp2(1.5) is 2 × √2 ≈ 2.828. - Not only integers. Any double exponent is allowed.
- Link with -lm. Needed on many GCC setups.
Frequently Asked Questions
exp2() returns 2 raised to the power x. exp2(3) is 8.
x is required. It is the double exponent for base 2.
A positive double equal to 2^x. Negative x returns a fraction.
Include <math.h>. On GCC, link with -lm.
exp() uses base e. exp2() uses base 2. Use exp2 when you want powers of two.
CODETOFUN NEWS
Stay Ahead in Tech
Get the latest IT news, programming updates, and technology trends directly on your phone.
About the author
Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
9 people found this page helpful