5

It seems (seemed) intuitive to me that there is no need to convert lower uints (e.g. uint8) to higher ones (uint256) within a formula. As I understood from the solidity docs it should be done automatically.

Am I wrong? Why am I getting "premature" overflows in the functions below?

This function works well until numSold is lower or equal to 15999. After that there is overflow.

function debugPower (uint16 numSold) public constant returns (uint) {
    return uint(2 ** (numSold/1000));
}

This function works well until numSold is lower or equal to 6999. Then overflow.

function debugPrice (uint8 x1, uint8 y1, uint16 numSold) private returns (uint80) {
    return uint80(1 finney * (2 ** (numSold/1000))); 
}

The same as above setting_delay never even close to uint32, currentLevel never close to uint16 and the final result never close to uint.

function debugActivationTime (uint32 setting_delay, uint16 currentLevel) public constant returns (uint32) {
    return uint32(now + ((2**(currentLevel-1)) * setting_delay)); 
}
  • waiting for the answer i had the same question – PHD LAB Oct 20 '16 at 20:54
2

The issue is that this expression:

return uint(2 ** (numSold/1000));

first evaluates 2 ** (numSold/1000), and deduces the resulting type from the type of numSold. So the truncation is happening before the value can ever be cast. The solution is to cast numSold to a uint first.

i.e.

return 2 ** uint(numSold/1000);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.