0

I have the following code:

function test_bytes(bytes32 test) external pure returns(bytes3 idx,uint256 idx2)
    {   

        //test = 0x885094be76a41df2b315d2e669de00bb0fa1333efa1fe9d200e304c490989680

        assembly{
            calldatacopy(0x0,33,36)
            idx := mload(0x0)  //0x989680
            idx2 := mload(add(idx, 32))  //10000000 
        }

the idx value gets bytes3 equal to 0x989680 which is correct, that value is required to convert to uint256 and store it in idx2. With the function shown I get a gas error.

1 Answer 1

0

I don't understand what exactly are you trying to do. But if you want to extract the last 3 bytes from the test parameter I would do it in the following way

contract X {
    function test_bytes(bytes32 test) external pure returns(bytes3 idx,uint256 idx2) {   
        // test = 0x885094be76a41df2b315d2e669de00bb0fa1333efa1fe9d200e304c490989680

        assembly {
            idx := shl(sub(256, 24), test)
            idx2 := and(test, 0xffffff)
        }
    }
}
  • idx is declared as bytes3 so we need to move the bytes we need to the "left". I do that with the shift left operator shl(sub(256, 24), test).

  • idx2 is declared as uint256 so the interesting bits must be to the right. Since the bytes are already there we only need to mask out the last bytes and(test, 0xffffff).

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.