3

bytes4 is a commonly needed data type in Solidity, due to its use in msg.sig and, more broadly speaking, in function selectors (e.g. Contract.func.selector).

How can one convert bytes4 to bytes memory?

2
  • can we just use direct conversion bytes memory convertedData = new bytes256(msg.sig)?
    – Gleichmut
    Feb 13 at 10:33
  • 1
    bytes256 doesn't exist as a type. But, assuming you meant bytes32, no, you can't do that. Feb 13 at 10:57

2 Answers 2

2

abi.encodeWithSelector can be used for this:

bytes memory a = abi.encodeWithSelector(msg.sig);
bytes memory b = abi.encodeWithSelector(Contract.func.selector);
1

You can do it directly using abi.encode() or abi.encodePacked().

function get(bytes4 _val) public pure returns(bytes memory) {
        return abi.encode(_val);
}

Example:

Input: 0x60c06040

Output: 0x60c0604000000000000000000000000000000000000000000000000000000000

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.