Solidity – Conversion from Bytes Memory to Uint Explained

contract-developmentsoliditytruffle-compile

Is there a workaround to convert a bytes memory to uint256?

Best Answer

It's possible but there's no easy way to do it. You either have to do some bitwise xor and shifting to build the uint, or use inline assembly to mload.

Here's the working code, feel free to copy paste

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;
}