0

In assembly, how do I grab the last 32 bytes in a 64-bytes input?

I know that this code is for grabbing the first 32:

bytes32 half;

assembly {
   half := mload(add(accData2, 32))
}

1 Answer 1

1

Consider this example:

// input 64 bytes 0x11112233445566778899aabbccddeeff00112233445566778899aabbccddeeff22112233445566778899aabbccddeeff00112233445566778899aabbccddeeff
// input 64 bytes 0x11111111111111111111111111111111111111111111111111111111111111112222222222222222222222222222222222222222222222222222222222222222
contract Bytes {
    function getLast32Bytes(bytes memory input) public returns (bytes32 half) {
        require(input.length == 64, "input must be exactly 64 bytes");

        assembly {
            half := mload(add(input, 64))
        }
    }

    function getFirst32Bytes(bytes memory input) public returns (bytes32 half) {
        require(input.length == 64, "input must be exactly 64 bytes");

        assembly {
            half := mload(add(input, 32))
        }
    }
}
3
  • mmmm gotcha! I think I know where my confusion lies thanks to your answer. So if, for example, I merge two bytes32 into one bytes (since there's no bytes64), the first 32 bytes will always be the length of that new bytes array? Regardless of whether that "merge" is only 64 bytes of data?
    – dNyrM
    Jan 19 at 11:54
  • I've updated the answer with example contract, previous answer could be misleading Jan 19 at 12:11
  • In getFirst32Bytes, if you're leaving an offset of 32 bytes before reading the beginning of the actual data, what's that offset? The length of the bytes array?
    – dNyrM
    Jan 19 at 13:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.