when I am using below function to convert bytes memory to address, this is working fine.
Suppose input to the function is 0X0000000000000000000000004af3246b4fff356261136f113411cb187134D675
I am getting the output 0x4af3246b4fff356261136f113411cb187134D675
function bytesToAddress(bytes memory bys) public pure returns (address addr) {
assembly {
addr := mload(add(add(bys, 32), 0))
}
}
Can, anyone explain me, what actually happening ?
Best Answer
The expression
add(bys, 32)
:Returns a pointer to the actual data, which starts after the first 32 bytes in the
bys
array (those first 32 bytes contain the length of thebys
array).The expression
mload(x)
:Loads the data pointed to by
x
, so you can just as well usemload(add(bys, 32))
, because there is no added value in doingx + 0
.The expression
addr := y
:Stores the value of
y
into the variableaddr
(in your case, since the value ofy
is 32-byte long and the type ofaddr
is 20-byte long, only the 20 least significant bytes are stored).