7

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

Stefano Angieri
  • 153
  • 1
  • 7
  • Duplicate of https://ethereum.stackexchange.com/questions/41944/hexadecimal-bytes-to-binary-uint-in-a-smart-contract – Alex G.P. May 22 '18 at 15:35
  • 2
    Actually is not the same question, since bytes is a dynamically-sized byte array, while bytes8 is not. – bordalix May 22 '18 at 15:49
  • 1
    Indeed trying to do the same of ethereum.stackexchange.com/questions/41944/ we have the following compiler error: " TypeError: Explicit type conversion not allowed from "bytes memory" to "uint256" – Stefano Angieri May 22 '18 at 15:53

3 Answers3

9

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;
}
libertylocked
  • 1,368
  • 8
  • 16
0

You cannot cast bytes to uint256, since bytes is a dynamically-sized byte array.

If you really need to do this conversion, use bytes32 (or any other fixed sized byte array) instead of bytes and then convert it to uint256 by a simple cast:

function two(bytes32 inBytes) pure public returns (uint256 outUint) {
      return uint256(inBytes);
}
bordalix
  • 918
  • 7
  • 11
  • The problem is that I need to work with dynamically-sized byte array.

    Another question: Is not possible to cast dynamically-sized byte array to fixed sized byte array?

    – Stefano Angieri May 22 '18 at 16:09
  • Think about this: how can you to convert a dynamically-sized array thats bigger then a fixed sized array? It won't fit ;) – bordalix May 23 '18 at 14:07
  • this doesn't work in solc 0.5.x, any idea how to convert fixed size byte arrays to and from uint? – okwme Sep 22 '19 at 15:09
0

Is possible to simply cast bytes memory to string and then use the stringToUint function I found in the Answer: How to convert string to int.

Stefano Angieri
  • 153
  • 1
  • 7