1

May I know why I can't do additional in uint for solidity 4.24?

function ToUint(bytes memory value) internal pure returns (uint) {
    uint r;
    for (uint i = value.length - 1; i >= 0; i--)
        r = (r << 8) + uint(value[i]);
    return r;
}

I might have over simplified my code and it doesn't exhibit the problem. The original code was above. As soon as I took out (r << 8) +, every thing works.

The << 8 is not an issue. Because it failed even when I have r + uint(value[I])

The length of bytes array is only 6, and all bytes value are < 0x7F

  • 1
    Could you post the code and the error? – Henk Aug 8 '18 at 5:53
  • What is the incentive for giving an upvote here??? There is no minimal coding example which reproduces the described problem, which shouldn't even take place under normal circumstances!!! – goodvibration Aug 8 '18 at 6:18
2

You will have problems with the loop

for (uint i = value.length - 1; i >= 0; i--)

Since i is unsigned once it reaches 0 in the next iteration it will wrap to a very large number becuase i cannot be a negative number.

1

It does work. You can add uint as per here. I also tried it in Remix.

1

You were accessing the elements of value wrong, which was causing the reversion.

Here's a working version:

pragma solidity 0.4.24;

contract BytesToUint {

    function toUint(bytes _value) external pure returns (uint) {
        return toUint_(_value);
    }

    function toUint_(bytes memory _value) internal pure returns (uint) {
        uint256 r;

        for(uint256 i = 0; i < _value.length; i++) {
            r += uint256(_value[i]) << (i * 8);
        }
        return r;
    }
}

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.