1

I want to calculate x^y (power of x to y) where x and y are both int32_t's. The result should be the same. If there is an overflow (also meaning: outside the bound of an int32_t, I want to catch that overflow - preferably before it even happens.

How is that possible?

(I know there are relevant __builtin methods for addition/subtraction/multiplication, but I don't think exponentation has one...)

Dr.Kameleon
  • 22,532
  • 20
  • 115
  • 223
  • Please clarify if you want to perfrom a pow or an XOR becouse the operator ^ performs an XOR. – ieio Jan 10 '20 at 08:14
  • @ieio I need a `pow`, I used the `^` notation as this is the one I normally use in "pseudocode" for exponentation... – Dr.Kameleon Jan 10 '20 at 08:29
  • Is `pow` from math.h not okay? You can check the result for overflow before converting to an integer, and all 32-bit integers can be represented precisely by a `double`. – Ry- Jan 10 '20 at 08:47
  • Have you already seen https://stackoverflow.com/questions/18609085/how-can-i-check-if-stdpow-will-overflow-double? It uses an algebric formulas wth logaritms it can tell you if there will be an overflow, I think you can adapt it for integer. Unfurtunately it consumes CPU. – ieio Jan 10 '20 at 08:51

1 Answers1

1

You could use your own implementation of pow for integer values (The most efficient way to implement an integer based power function pow(int, int); see also the comments) and then use the built-in overflow checks for multiplication within that function.

It depends on your use case whether it is worthwhile doing so. Alternatively you could detect the overflow after the fact by inspecting the implementation dependent error result.

J.R.
  • 1,880
  • 8
  • 16