Q:

Solidity: Saving arbitrary data into bytes array and later parsing it

I want to create a function that receives two addresses and saves them into a bytes array.
later a matching function will receive this bytes array and parse the two addresses.
function addressesToBytes(address add1, address add2) public view returns(bytes combined) {
    combined = new bytes(40); //since each address is 20 bytes
    //store the two addresses in the bytes array
}

function bytesToAddresses(bytes combined) returnes(address add1, address add2) {
     // here set add1 and add2 values from combined bytes array
}

I saw this answer. but it was not enough :(.

A:

This will get the job done:
pragma solidity ^0.5.1;

contract Encoding {

    function encode(address _address1, address _address2) public pure returns (bytes memory output) {
        return abi.encodePacked(_address1, _address2);
    }

    function decode(bytes memory _encoded) public pure returns (address x, address y) {
        assembly {
            x := mload(0x94)
            y := mload(0xa8)
        }
    }
}

These functions are also pretty efficient. The encoding function takes around 900 gas for execution and the decoding function only around 670.

