function toBytes(address a) public pure returns (bytes memory b){
assembly {
let m := mload(0x40)
a := and(a, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
mstore(add(m, 20), xor(0x140000000000000000000000000000000000000000, a))
mstore(0x40, add(m, 52))
b := m
}
}
Takes just 695 gas vs 2500 for Gokulnath's answer and 5000 for Eth's
Edit for solidity ^0.5.0:
This is almost as efficient and much more readable:
function toBytes(address a) public pure returns (bytes memory) {
return abi.encodePacked(a);
}
Best Answer
It seems there now is, since solidity version 0.4.24 you can use abi.encodePacked
E.G: