How do I grab the last 12 bytes of a bytes32 in assembly?

For example, the last 12 bytes of bytes32 num = 0xdeb02111e4e5fa8c7c05e983a3446893a36d12ad6d79206163636f756e740000


1 Answer 1


There are multiple ways to do it on solidity using explicit type cast or convert to bytes and use index slicing, but if you want to do it in assembly the best way is to shift left 160 bit using shl(160,num). This leaves you 96 bits (12 bytes) on the most significant bytes. You can cast them to your bytes12 type afterward:

contract Test{
    function test() public view returns(bytes12){
        bytes32 num = 0xdeb02111e4e5fa8c7c05e983a3446893a36d12ad6d79206163636f756e740000;
        bytes12 res1 = bytes12(uint96(uint256(num)));
        bytes12 res2 = bytes12(num<<160);
        bytes12 res3;
        assembly {
            res3 := shl(160,num)
        require(res1 == res2);
        require(res2 == res3);
        return res3;

Output : 0:bytes12: 0x6d79206163636f756e740000

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.