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.