I understand what add()
does. It used used in the assembly to perform additions. My question is why are we adding 32 here? What is the purpose of doing so?
The full code is here
I understand what add()
does. It used used in the assembly to perform additions. My question is why are we adding 32 here? What is the purpose of doing so?
The full code is here
To better understand it is better to include part of the function
function stringToBytes32(string memory source) public pure returns (bytes32 result) {
// ..
assembly {
result := mload(add(source, 32))
}
}
source
is a memory string so the first 32 bytes contains the length and data follows. Then add(source, 32)
skips the size portion of the string, and points to the data.
With an example:
function myfunc(bytes[] calldata data) public view {
bytes memory _data = data[0];
bytes32 dat1;
bytes32 dat2;
assembly {
dat1 := mload(_data)
dat2 := mload(add(_data, 32))
}
console.logBytes32(dat1);
console.logBytes32(dat2);
}
Calling the function with input as ["0x775c300c"]
Every two character in hex corresponds to a single byte so the above is 4 bytes.
Output:
0x0000000000000000000000000000000000000000000000000000000000000004
0x775c300c00000000000000000000000000000000000000000000000000000000
As we can see that the first 32 bytes is the length and the next 32 bytes is the data.