Does solidity supports power operations like 2^3 = 8 or should I perform multiple multiplications? Should i include a math library? I don't find anything in the official doc. Thanks
** is the operator you are looking for. 2**3 = 8.
But be paranoid when using it - it is very easy to overflow.
For example... in the case of 255 to the second power... the answer you probably want is 65025. However, if you used a uint8, then what are you actually getting is 65025 mod (2^8), or, 1.
uint8 a = 255; uint8 b = 2; uint8 c = a**b;
results in c being equal to 1.
Even the following does you no good. Since a and b are both uint8s, the result is a uint8 with the "feature" of a mod 2^8, before being cast to a uint256.
uint256 d = a**b;
Once again, d would equal 1.
The following gets you the right answer, but only because a and b are so small.
uint256 e = uint256(a)**uint256(b);
e equals 65025.
A sophisticated approach to make sure you are safe is here...
A simpler rule of thumb: if you take a number that's 255 or less, to the power of 32 or less, you should be okay.
Remember that (a^b)^c equals a^(b*c).
So taking the max uint8, 255...
255^255 < 256^255 = (2^8)^255 = 2^(8x255) = 2^(2040)
which is clearly more bits than a "tiny" uint256 can hold (2^256 - 1)...
255 ^ 32 < 256 ^ 32 = (2^8)^32 = 2^(8*32) = 2^256 = one less than the maximum value of a uint256