6

Hey is there a way to convert bytes to uint in Solidity?

  • Could you explain what conversion you would like? Best if you can give an example of a bytes value and the corresponding uint value you would like to see. – user19510 Jun 14 '18 at 14:52
4

You can use this function to convert bytes to unit:

pragma solidity ^0.4.23;

contract mycontract {

    function bytesToUint(bytes b) public 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;
    }
}

The amount of gas used depends on the length of your bytes variable, but this is cheap. Converting a bytes variable of length 20 uses about 420 gas.

Hope this helps

  • Getting an error in Remix: TypeError: Return argument type bytes memory is not implicitly convertible to expected type uint256 – arete Jun 14 '18 at 15:02
  • Can you show me your code?, this works for me well in remix, I put the whole code so you can just copy and paste it. Let me know – Jaime Jun 14 '18 at 15:13
  • Oh there you go. I think your first post had the return value as "b". This works. Thanks! – arete Jun 14 '18 at 15:25
  • Good, if this answers your question, please accept it. – Jaime Jun 14 '18 at 15:31
1

Slicing an uint out of bytes using inline assembly

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

The fully working modern solution from Consensys dude can be found here:

https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol

The accepted answer's code is not compiling in Solidity >0.5; with implicit type conversion error.

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.