In Solidity function signatures are 4 bytes long and the formula to generate it is to hash it with the keccak256 function, like so:


The first 4 bytes of msg.data are the method signature. How can I extract those 4 bytes from `msg.data (using Solidity of course)?

  • 1
    You just read the first 4 bytes of msg.data. You can do that using assembly { mload / mstore } or just access the msg.data as a byte array ( msg.data[0 to 3] ). What exactly are you trying to achieve by this ? Nov 6, 2018 at 8:46
  • 1
    I need to know the what is the hashed signature of the calling method. What I'm trying to achieve is not the issue here.
    – forhas
    Nov 6, 2018 at 9:53

1 Answer 1


In the section about Special Variables and Functions of the Solidity documentation, the special variable msg.sig is reported.

Here I report a minimal example that works with remix:

pragma solidity ^0.4.24;

contract GetYourSig {
    function f() public pure returns (bytes4) {
        return msg.sig;

If you really want to extract the signature directly from msg.data, you can use some bit manipulation:

pragma solidity ^0.4.24;

contract GetYourSigFromMsgData {
    function f() public pure returns (bytes4) {
        return (bytes4(msg.data[0]) | bytes4(msg.data[1]) >> 8 |
            bytes4(msg.data[2]) >> 16 | bytes4(msg.data[3]) >> 24);

It is worth noting that you have to cast the msg.data[i] elements to bytes4 before performing the shifting, otherwise it does not work.

Obviously, the latter approach requires more gas than the previous one (824 and 229, respectively).

If you want you can achieve the same result with assembly as suggested in the comment.

  • @forhas, please see my edit, and consider to upvote the question ^^
    – Briomkez
    Nov 6, 2018 at 16:53
  • Is there a way to extract the function signature from an encoded transaction?
    – BonisTech
    Apr 19, 2022 at 2:13

Your Answer

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

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