Solidity Conversion – Convert Bytes Memory to Address Type in Solidity

blockchaingo-ethereumsoliditysolidity-0.6.x

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 the bys array).


The expression mload(x):

Loads the data pointed to by x, so you can just as well use mload(add(bys, 32)), because there is no added value in doing x + 0.


The expression addr := y:

Stores the value of y into the variable addr (in your case, since the value of y is 32-byte long and the type of addr is 20-byte long, only the 20 least significant bytes are stored).

Related Topic