1

I'm looking to convert a bytes into an int.

For example, this works in Solidity 0.4.23, but fails to explicit type conversion error in later versions.

function bytesToUint(bytes memory b) public view returns (uint256){
    uint256 number;
    for(uint i=0;i<b.length;i++){
        number = number + uint(b[i])*(2**(8*(b.length-(i+1))));
    }
    return number;
}

Does anybody know how to do this in later versions of solidity?

2 Answers 2

1

Bytes is a tightly packed array of bytes1.

Since Solidity 0.5.0 this change was introduced :

Type Checker: Disallow conversions between bytesX and uintY of different size.

Given that the current doc states that :

uint and int are aliases for uint256 and int256, respectively.

Your syntax tries to cast a bytes1 to uint256, this is forbidden since 0.5.0.

You can achieve your goal by just being more precise on the types, see this example :

pragma solidity ^0.8;

contract MyContract {
    
    function bytesToUint(bytes memory b) public pure returns (uint256){
        uint256 number;
        for(uint i=0;i<b.length;i++){
            number = number + uint8(b[i]);
        }
        return number;
    }

}

The only important change is uint8(b[i]) instead of uint(b[i[). Casting bytes1 to a type of equal length.

So for an explicit conversion from bytes (containing tightly packed bytes1) you need :

uint(uint8(b[i]))

But anyway, implicit conversion from uint8 to uint is perfectly fine as in the previous exemple.

Hope that helps !

1

I was having issues with hroussille's answer. This answer worked for me

function sliceUint(bytes bs, uint start)
    internal pure
    returns (uint)
{
    require(bs.length >= start + 32, "slicing out of range");
    uint x;
    assembly {
        x := mload(add(bs, add(0x20, start)))
    }
    return x;
}

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.