## Exponents in GCC

14 posts / 0 new
Author
Message

WARNING: I'm a GCC newb.

I'm only including , so that might be an issue (a missing header file that I need), but the following lines of code:

uint8_t x = 2;
uint8_t y = 5;
uint8_t z = 0;

z = x^y;

Does not give me the desired result. Is there a way to do exponents in AVR-GCC without having to do a for loop? Or should I just program a function that does just that?

Thanks!

Looking at standard C programming, I think I may be needing to include math.h and try:

z = pow(x, y);

And I might need to retype my variables. Can anyone confirm this for me?

^ is XOR ;)

pow() is defined as double pow(double,double) IIRC so it will bring in some heavy floating point libraries.

If you just want integer powers and work with integer values, then by all means, write a subroutine with a loop by yourself. If for no other reason than to avoid floating point calculations.

- Jani

Good to know!

Thank you both for the information. It's been a long time since I've programmed standard C (been a PHP & C#/VB.NET programmer for a few years now) and I've been spoiled by interpreted languages doing everything for me. Gotta get out of that habit!

If you're only writing powers of 2, just use left shift: 1<<x is 2 to the power of x. avr-libc comes with a macro in avr/sfr_defs.h called _BV(x).

```
/**
* Recursive code to calculate the values with exponents.
* @param base is the value being mulitplied by itself.
* @param exponent is the number of the times the base is being multiplied
* by itself.
* /

unsigned long power(unsigned int base, unsigned int exponent)
{
if (exponent == 0)
{
return 1;
}

return base * power(base, exponent - 1);
}
```

Came here for an answer. Decided to make a quick solution using recursion.

Woah

11 years too late (and who would use recursion on a low RAM device?)

Also why wouldn't one simply use pow() from the C library?

I am an engineering student. Didn't realize recursion would be an issue. Thanks for the heads up.

Woah

clawson wrote:
Integers.

Moderation in all things. -- ancient proverb

`(int)pow()`

Integers.

IEEE754 guarantees exact representations of integers from -(224-1) to +(224-1) for 32-bit floats, so when using:

`(int)pow()`

... with an integer base, an integer exponent, and an integer result within that range, no precision will be lost.  However, it will suffer the same speed and size penalties of using floats.

 "Experience is what enables you to recognise a mistake the second time you make it." "Good judgement comes from experience.  Experience comes from bad judgement." "Wisdom is always wont to arrive late, and to be a little approximate on first possession." "When you hear hoofbeats, think horses, not unicorns." "Fast.  Cheap.  Good.  Pick two." "We see a lot of arses on handlebars around here." - [J Ekdahl]

Last Edited: Mon. Mar 26, 2018 - 05:42 AM