Is there a workaround to convert a bytes memory to uint256?
-
Duplicate of ethereum.stackexchange.com/questions/41944/… – Alex G.P. May 22 '18 at 15:35
-
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
-
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
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;
}
-
This should be the accepted answer. Works great, thanks @libertylocked – The Nomad Jul 30 '18 at 6:18
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);
}
-
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
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.